String Methods
Strings come with over forty built-in methods. This lesson groups the most useful ones by job — changing case, cleaning whitespace, searching, replacing, splitting and testing — so you know where to look when you need one.
Changing case
s = "hello wORLD" print(s.upper()) print(s.lower()) print(s.title()) print(s.capitalize()) print(s.swapcase()) print("Straße".casefold())
HELLO WORLD hello world Hello World Hello world HELLO World strasse
casefold() is a stronger version of lower() designed for case-insensitive comparisons across languages.
Removing whitespace and characters
raw = " padded text \n" print(repr(raw.strip())) print(repr(raw.lstrip())) print(repr(raw.rstrip())) print("***bold***".strip("*")) print("report_final.pdf".removesuffix(".pdf")) print("Mr. Smith".removeprefix("Mr. "))
'padded text' 'padded text \n' ' padded text' bold report_final Smith
strip() removes any of the given characters from both ends (whitespace by default). To remove an exact prefix or suffix, use removeprefix/removesuffix — strip would remove matching characters one at a time, which is a classic bug.
Searching
s = "the rain in spain" print(s.find("ain")) print(s.rfind("ain")) print(s.find("snow")) print(s.count("ain")) print(s.startswith("the"), s.endswith(("ain", "ow"))) print(s.index("rain"))
5 14 -1 2 True True 4
find returns -1 if not found, while index raises a ValueError. startswith and endswith accept a tuple to test several options at once. For a simple yes/no, use the in operator.
Replacing
s = "one, two, two, three" print(s.replace("two", "2")) print(s.replace("two", "2", 1)) print("a-b_c".translate(str.maketrans("-_", " ")))
one, 2, 2, three one, 2, two, three a b c
Splitting and joining
csv_line = "Ana,31,Lisbon" print(csv_line.split(",")) print(" lots of space ".split()) print("a=1=2".split("=", 1)) print("line1\nline2\nline3".splitlines()) print("user@example.com".partition("@")) print(" | ".join(["red", "green", "blue"]))
['Ana', '31', 'Lisbon']
['lots', 'of', 'space']
['a', '1=2']
['line1', 'line2', 'line3']
('user', '@', 'example.com')
red | green | bluesplit() with no argument splits on any run of whitespace and ignores leading/trailing spaces. partition splits once into exactly three parts. join is called on the separator and takes an iterable of strings.
Alignment and padding
for item, price in [("Tea", 3), ("Cake", 4.5), ("Sandwich", 7.25)]: print(item.ljust(10, ".") + f"{price:>6.2f}") print("42".zfill(5)) print("title".center(15, "~"))
Tea....... 3.00 Cake...... 4.50 Sandwich.. 7.25 00042 ~~~~~title~~~~~
Testing content
print("12345".isdigit(), "12.5".isdigit()) print("Hello".isalpha(), "Hello1".isalnum()) print(" ".isspace(), "Title Case".istitle()) print("ABC".isupper(), "abc".islower()) print("my_var".isidentifier())
True False True True True True True True True
These are handy for quick validation, but note "12.5".isdigit() is false — to check whether a string is a valid number, try converting it with float() instead.
Chaining methods
title = " Hello, World! Welcome to Python. " slug = ( title.strip() .lower() .replace(",", "") .replace("!", "") .replace(".", "") .replace(" ", "-") ) print(slug)
hello-world-welcome-to-python
Quick reference
| Job | Methods |
|---|---|
| Case | upper lower title capitalize swapcase casefold |
| Trim | strip lstrip rstrip removeprefix removesuffix |
| Search | find rfind index count startswith endswith |
| Replace | replace translate expandtabs |
| Split / join | split rsplit splitlines partition join |
| Align | ljust rjust center zfill |
| Test | isdigit isalpha isalnum isspace isupper islower |