Python strings come with more than forty methods, and you will end up using about eight of them in nearly every program you write. The problem is that several of those eight behave in a way that the name does not suggest, and the trap only shows itself once. This lesson covers the daily drivers properly: cleaning whitespace, splitting text, changing case, testing prefixes, and the family of is predicates that decide whether a string holds a number.
The previous lesson in this module covered "Indexing and Slicing Strings Like a Pro", and the next lesson in this module is about "Why Strings Are Immutable (and Why It Matters)".
How do you clean up whitespace in a string?
Three methods handle the edges of a string. strip() removes whitespace from both ends, lstrip() removes it from the left, and rstrip() removes it from the right. The name is slightly misleading, because "strip" can also mean "remove these particular characters", and when you pass an argument it removes any of those characters from both ends instead of removing a prefix or a suffix.
raw = ' \tTutorsbot \n'
print('raw ->', repr(raw))
print('stripped ->', repr(raw.strip()))
print('left only ->', repr(raw.lstrip()))
print('right only ->', repr(raw.rstrip()))
print('strip set ->', repr('xyxTutorsbotxy'.strip('xy')))
print('split ->', 'a b \t c'.split())
print('split sep ->', 'a, b,, c'.split(','))
print('split max ->', 'a, b,, c'.split(',', 1))
Look at the two splitting results, because they behave differently. 'a b \t c'.split() with no separator splits on runs of whitespace and drops the empty pieces, which is exactly what you want when you are parsing a line of text. 'a, b,, c'.split(',') splits on every comma and keeps the empty piece in the middle, and that empty piece is usually a problem in the data rather than a problem in your code.
Both behaviours are worth knowing on purpose. Splitting with no argument is the forgiving version, and splitting with an explicit separator is the literal version that will happily hand you empty strings that you then have to filter out yourself.
How do you change the case of a string?
Six methods cover the work of changing case, and one of them is a trap. upper() and lower() are obvious. capitalize() uppercases the first character and lowercases the rest. swapcase() flips the case of every character. casefold() is the aggressive one, and it is the right tool when you are comparing text that might contain accents.
name = 'ada lovelace'
print('upper ->', name.upper())
print('lower ->', name.lower())
print('title ->', name.title())
print('capitalize ->', name.capitalize())
print('swapcase ->', 'AbC'.swapcase())
print('title trap ->', "don't".title())
print('casefold ->', 'Straße'.casefold())
print('lower ->', 'Straße'.lower())
The trap is title(). It treats every non-letter as the end of a word, which means that an apostrophe starts a new word, so "don't" becomes "Don'T". It also turns "ada lovelace" into "Ada Lovelace", which is what you want for a display name and completely wrong for a sentence. If you need sentence case, take the first character and the rest of the text separately instead of reaching for title().
The last two lines show why casefold() exists. The German sharp s lowercases to 'ß', but it casefolds to 'ss', and that is the form you want when you are comparing two strings for equality. Use lower() when you are displaying text, and use casefold() when you are comparing it.
Which checks and predicates save you the most time?
A small group of methods answers questions so often that you should reach for them without thinking. startswith() and endswith() test the edges of a string, and both of them accept a tuple so that you can check several possibilities at once. removeprefix() and removesuffix(), which arrived in Python 3.9, remove a known prefix or suffix and return the string unchanged when it is not there. partition() splits a string into three parts around the first occurrence of a separator.
filename = 'report-final.pdf'
print('startswith ->', filename.startswith('report'))
print('endswith ->', filename.endswith('.pdf'))
print('tuple form ->', filename.startswith(('report', 'summary')))
print('removeprefix ->', filename.removeprefix('report-'))
print('removesuffix ->', filename.removesuffix('.pdf'))
print('no match ->', filename.removeprefix('other-'))
head, separator, tail = 'key=value=extra'.partition('=')
print('partition ->', head, separator, tail)
Then there is the family of predicates that answer questions about the content of a string. isalpha(), isdigit(), isalnum(), isspace(), isupper(), islower(), and istitle() each return a boolean, and every one of them returns False for an empty string instead of raising an error.
samples = ['abc', '123', '1.5', '', ' ']
for text in samples:
print(repr(text), 'isalpha:', text.isalpha(), 'isdigit:', text.isdigit())
Notice that '1.5' is neither alphabetic nor a digit, because of the decimal point. Also notice that a superscript two counts as a digit, and that matters if you are validating a PIN. isdigit() accepts characters that int() will refuse to convert, so a form can pass your check and then fail later at the conversion step.
What should you reach for instead of string methods?
String methods handle structure. Patterns need the re module, which the next lesson covers in detail. Structured data needs the json and csv modules, which the lesson after that covers. Knowing which problem you actually have saves you from writing a regular expression when a simple split() would do, and it saves you from parsing JSON by hand with find() when a single json.loads() call is both shorter and correct.
Two more habits keep string handling tidy. Reach for str.replace() when you want every occurrence replaced, and reach for the re module when you need a pattern or a single replacement. And when you build output, reach for f-strings rather than chaining replace() calls to reshape a template.
There is one more method that is worth knowing for cleanup work. str.translate() takes a translation table and maps every character through it, which is how you delete a known set of characters in a single pass instead of chaining replace() calls. The table comes from str.maketrans(), which accepts the characters to delete and what should replace them.
noisy = 'Order #42 (paid) - 2026/10/27!'
remove_punctuation = str.maketrans('', '', '()#-/')
print('cleaned ->', noisy.translate(remove_punctuation))
digits_to_zero = str.maketrans('0123456789', '##########')
print('masked ->', 'a1b2c3'.translate(digits_to_zero))
Compare that with the alternative of chaining five replace() calls, which gives the same result and reads much worse. The translation table is also faster, because the string is walked once instead of once for every rule.
Your turn: write a normaliser for messy input
- Write
normalise_username(raw)that removes surrounding whitespace, lowercases the text, replaces spaces with underscores, and removes a leading@. Test it with' @Ada Lovelace '. - Handle repeated underscores by collapsing them, and decide whether a name should be allowed to end with an underscore. Write your rule down as a comment.
- Add a validation step that rejects anything containing a character other than letters, digits, and underscores, and prints a clear message instead of raising an exception.
- Write a second helper,
normalise_title(text), that produces"Ada Lovelace"from"ada lovelace"without usingtitle(), so that"don't"survives intact. - Finally, build a report that reads a list of raw names and prints each one next to its normalised form and a yes-or-no validation result.
Method cheat sheet
strip(),lstrip(), andrstrip()remove whitespace, or a set of characters when you pass one in.split()with no argument splits on whitespace and drops empty pieces, whilesplit()with a separator splits literally and keeps them.- Use
casefold()for comparisons, and avoidtitle()on text that contains apostrophes. startswith()andendswith()accept tuples, andremoveprefix()andremovesuffix()remove a known edge.partition()splits a string into a head, a separator, and a tail at the first match.- The
is*predicates returnFalsefor empty strings, andisdigit()accepts characters thatint()rejects.