Sub topic 2
Python String Methods for Searching and Changing Text
Assume you know variables, string indexing, lists, tuples, and simple if statements and for loops. Python strings are immutable, so these methods return new strings instead of changing the original.
Testing how a string starts or ends
Use startswith() and endswith() for prefix and suffix checks. A prefix is text at the beginning. A suffix is text at the end. Both methods return True or False and accept a tuple of alternatives.
filename = "report.csv"
print(filename.startswith("report")) # True
print(filename.endswith((".csv", ".tsv"))) # True
print(filename.endswith(".pdf")) # FalseUse these methods when the boundary matters. Use the in operator when the text can occur anywhere.
Changing case
Case methods return copies:
word = "Python"
upper_word = word.upper()
lower_word = word.lower()
print(word) # Python
print(upper_word) # PYTHON
print(lower_word) # pythonOther useful methods include capitalize(), title(), and swapcase(). Choose the method that matches the desired output, rather than changing case repeatedly.
Case-insensitive searching and `casefold`
To compare ordinary English text without considering case, normalize both values first:
query = "PYTHON"
text = "Python programming"
print(query.casefold() in text.casefold()) # Truecasefold() is intended for caseless Unicode comparison. It is more aggressive than lower(). For example, "Straße".casefold() becomes "strasse", which matches "STRASSE".casefold().
>``callout note >Normalize both sides of a comparison. Converting only the search term or only the source text can produce a false negative. >``
Replacing text
replace(old, new) replaces every matching occurrence by default. Its third argument limits the number of replacements.
text = "a-b-c"
print(text.replace("-", "+")) # a+b+c
print(text.replace("-", "+", 1)) # a+b-cTrimming and removing exact boundaries
strip() removes listed characters from both ends, not a literal substring. lstrip() and rstrip() affect one side. Use removeprefix() and removesuffix() when the boundary text must match exactly.
value = " test_file.py\n"
print(repr(value.strip())) # 'test_file.py'
print("xxhixx".strip("x")) # hi
print(value.removesuffix("\n")) # ' test_file.py'
print("v1.2".removeprefix("v")) # 1.2Exercise
Which method removes one exact suffix, such as ".py", without treating its characters as a set?
Show answer
removesuffix(".py").