Working with text · Python How-To Guides

Short, practical answers for common string tasks. Each page leads with the answer, then shows runnable code, the output and a note on edge cases such as empty strings and mixed case.

All 7

How to Reverse a String in Python
Use slicing: `text[::-1]` returns a new string with the characters in reverse order. `"".join(reversed(text))` does the same thin…
How to Check if a String Contains a Substring in Python
Use the `in` operator: `"cat" in "concatenate"` returns `True` if the substring appears anywhere in the string and `False` otherw…
How to Remove Whitespace from a String in Python
Use `text.strip()` to remove whitespace from both ends, or `"".join(text.split())` to remove it everywhere, including spaces, tab…
How to Split a String into Words in Python
Call `text.split()` with no arguments: it splits on any whitespace and returns a list of words, such as `"to be or not".split()` …
How to Compare Strings Ignoring Case in Python
Convert both strings to the same case before comparing: `a.casefold() == b.casefold()` (or `a.lower() == b.lower()`) is `True` wh…
How to Pad a Number with Leading Zeros in Python
Use an f-string: `f"{7:03d}"` gives `'007'`. For text that is already a string, `"7".zfill(3)` gives the same `'007'`.
How to Capitalize the First Letter of a String in Python
`text.capitalize()` uppercases the first character and lowercases the rest; use `text[0].upper() + text[1:]` to change only the f…

Explore more

Python ReferencePython ProgramsPython ComparisonsPython Cheat SheetsPython glossaryPython tutorial