Python String Methods You Will Actually Use
Case conversion, whitespace trimming, searching, counting and the is-something tests, organised by the job they do rather than alphabetically.
- Basics
- Data Types
- Operators
- Strings
- Control Flow
- Lists
- Tuples
- Sets
- Dictionaries
- Comprehensions
- Functions
- Advanced Functions
- Recursion
- Exception Handling
- File Handling
- Modules
- Standard Library
- OOP
- Advanced OOP
- Iterators and Generators
- Decorators
- Context Managers
- Descriptors and Dataclasses
- Python Internals
- Concurrency
- Regular Expressions
- Serialization
- Command Line Python
- Testing and Debugging
- Type Hints
- Performance
- Python Security
- DSA with Python
Every method returns a new string
Strings are immutable, so no method on this page changes the original. Each one returns a new string that you must assign or use immediately.
name = " meera "
name.strip() # discarded
name = name.strip() # keptChanging case
| Method | Does | "hello WORLD" becomes |
|---|---|---|
upper() | Everything uppercase | HELLO WORLD |
lower() | Everything lowercase | hello world |
title() | First letter of each word | Hello World |
capitalize() | First letter only, rest lowercased | Hello world |
swapcase() | Inverts each letter | HELLO world |
casefold() | Aggressive lowercasing for comparison | hello world |
text = "hello WORLD"
print(text.upper(), text.title(), text.capitalize(), sep=" | ")
# casefold handles cases lower() does not
print("STRASSE".lower() == "straße".lower()) # False
print("STRASSE".casefold() == "straße".casefold()) # Truetitle()is naive: it capitalises after every non letter, so"it's"becomes"It'S". For real headings, capitalise words yourself.
Trimming whitespace
raw = "\t meera nair \n"
print(repr(raw.strip())) # 'meera nair' - both ends
print(repr(raw.lstrip())) # 'meera nair \n' - left only
print(repr(raw.rstrip())) # '\t meera nair' - right only
# strip removes any of the given CHARACTERS, not a prefix string
print("xxhelloxx".strip("x")) # hello
print("www.example.com".strip("cmowz.")) # example <- surprising
# For a genuine prefix or suffix, use these (Python 3.9+)
print("www.example.com".removeprefix("www.")) # example.com
print("report.txt".removesuffix(".txt")) # reportstrip("cmowz.") removed every leading and trailing character that appeared in that set. That is what strip does, and it catches people out constantly. Use removeprefix and removesuffix when you mean a specific string.
Searching
text = "python programming is programming"
print(text.find("programming")) # 7 - first index, or -1 if absent
print(text.find("java")) # -1 - no exception
print(text.rfind("programming")) # 21 - searching from the right
print(text.index("programming")) # 7
# print(text.index("java")) # ValueError
print(text.count("programming")) # 2
print(text.count("m")) # 4
print(text.startswith("python")) # True
print(text.endswith(("ing", "ed"))) # True - a tuple tests several suffixes
print(text.find("gram", 20)) # search starting at index 20| Found | Not found | Use when | |
|---|---|---|---|
find | index | -1 | Absence is normal |
index | index | ValueError | Absence is a bug |
in | True | False | You only need to know whether |
Replacing
text = "one two two three"
print(text.replace("two", "2")) # one 2 2 three
print(text.replace("two", "2", 1)) # one 2 two three - only the first
print(text.replace(" ", "")) # onetwotwothree
# Chained replacements read fine for a couple of cases
cleaned = text.replace(",", "").replace(".", "").strip()The is-something tests
All of these return True or False, and all of them return False for an empty string.
| Method | True when every character is |
|---|---|
isdigit() | A digit |
isnumeric() | Any numeric character, including fractions and Roman numerals |
isdecimal() | A plain decimal digit; the strictest of the three |
isalpha() | A letter |
isalnum() | A letter or a digit |
isspace() | Whitespace |
islower() / isupper() | Lowercase / uppercase (ignoring non letters) |
istitle() | Title cased |
isidentifier() | A legal Python name |
print("12345".isdigit()) # True
print("12.5".isdigit()) # False - the dot is not a digit
print("-5".isdigit()) # False - nor is the minus sign
print("".isdigit()) # False - empty is never true
print("abc123".isalnum()) # True
print("hello world".isalpha()) # False - the space is not a letter
print(" ".isspace()) # Trueisdigit()is not a number validator. It rejects"-5","12.5"and"1e3", all of which are valid numbers. To validate a number, try the conversion inside atryblock.
def is_number(text):
try:
float(text)
return True
except ValueError:
return False
print(is_number("-12.5"), is_number("abc")) # True FalsePadding and alignment
print("7".zfill(3)) # 007
print("-7".zfill(4)) # -007 - the sign stays in front
print("left".ljust(10, ".")) # left......
print("right".rjust(10, ".")) # .....right
print("mid".center(11, "-")) # ----mid----
for name, score in [("Meera", 92), ("Arun", 7)]:
print(name.ljust(10), str(score).rjust(3))A practical cleaning function
def clean_name(raw):
"""Normalise a name typed by a user."""
name = raw.strip()
name = " ".join(name.split()) # collapse repeated internal spaces
return name.title()
print(clean_name(" meera NAIR ")) # Meera NairCommon mistakes
- Not assigning the result of a method.
- Using
strip("abc")expecting it to remove the literal prefix"abc". - Using
isdigit()to validate numbers that may be negative or decimal. - Using
indexwherefindwas meant, and getting an unhandledValueError. - Trusting
title()on text containing apostrophes or hyphens. - Comparing user input without
casefold().
Best practices
- Use
inwhen you only need to know whether something is present. - Use
removeprefixandremovesuffixfor exact affixes. - Normalise input once, near the point of entry: strip, collapse spaces, casefold if comparing.
- Validate numbers by converting inside
try, not by inspecting characters.
Practice
- Explain why
"mississippi".strip("mip")returns"ss". - Write a function that reports whether a string is a valid Python identifier and is not a keyword.
- Format a table of five names and scores so the columns line up, using only
ljustandrjust. - Write a validator that accepts
"42","-42"and"4.2"but rejects"4 2"and"". - Count how many times each vowel appears in a sentence using
count.
Conclusion
The string methods divide into five jobs: change case, trim whitespace, search, replace and test. Learn one method well from each group and look the rest up. The two that will bite you are strip, which takes a character set rather than a prefix, and isdigit, which is not a number check.