Python String Methods Reference: str Methods, Syntax, and Examples
Python string methods are built-in functions on str objects that let you change, search, split, clean, and test text. They always return a new string or a simple value such as True, False, or an index; they do not change the original string because strings are immutable. This reference groups the most useful methods by task and shows the small details people often miss.
Difficulty: Beginner
Helpful to know first: basic Python syntax, variables, and how strings store text in quotes.
Text case methods for changing upper and lower letters
These methods return a new string with a different letter case. They are useful when you want text to look consistent, compare text without case differences, or normalize user input before saving it.
| Method | What it does | Example |
|---|---|---|
| upper() | Converts letters to uppercase. | "python".upper() → "PYTHON" |
| lower() | Converts letters to lowercase. | "Python".lower() → "python" |
| capitalize() | Makes the first character uppercase and the rest lowercase. | "heLLo".capitalize() → "Hello" |
| title() | Capitalizes the first letter of each word. | "hello world".title() → "Hello World" |
| swapcase() | Swaps uppercase letters to lowercase and lowercase letters to uppercase. | "PyThOn".swapcase() → "pYtHoN" |
How these methods behave
String case methods do not modify the original value. They create a new string and leave the old one alone.
text = "Python"
upper_text = text.upper()
print(text)
print(upper_text)
# Output:
# Python
# PYTHONUse these methods when you need a new version of the text. If you want to compare values, convert both sides to the same case first.
Cleaning and trimming whitespace from strings
These methods remove characters from the ends of a string. They are commonly used when reading form input, file lines, or text with extra spaces and newline characters.
| Method | What it removes | Example |
|---|---|---|
| strip() | Whitespace from both ends, or specific characters if provided. | " hi ".strip() → "hi" |
| lstrip() | Whitespace or specific characters from the left side. | " hi ".lstrip() → "hi " |
| rstrip() | Whitespace or specific characters from the right side. | " hi ".rstrip() → " hi" |
When no argument is given, these methods remove whitespace characters such as spaces, tabs, and newlines. They do not remove text from the middle of the string.
Using strip() with specific characters
You can pass a string of characters to remove from the ends. Python removes any of those characters repeatedly until a different character appears.
filename = "...report.txt..."
print(filename.strip("."))
# Output: report.txtThis is useful for cleaning wrapper characters, but it is not the same as removing a whole substring. For example, strip("abc") does not remove the exact text "abc"; it removes any combination of a, b, or c from the ends.
Checking what kind of text you have
These methods answer a yes-or-no question. They return True or False, so they are good for validation and simple input checks.
| Method | Meaning | Example |
|---|---|---|
| isalpha() | All characters are letters and the string is not empty. | "Python".isalpha() → True |
| isdigit() | All characters are digits. | "123".isdigit() → True |
| isalnum() | All characters are letters or digits. | "Python3".isalnum() → True |
| isspace() | All characters are whitespace. | " \n".isspace() → True |
| islower() | At least one cased letter exists and all cased letters are lowercase. | "python".islower() → True |
| isupper() | At least one cased letter exists and all cased letters are uppercase. | "PYTHON".isupper() → True |
Why validation methods can surprise you
These methods are stricter than many beginners expect. For example, "123.45".isdigit() is False because the period is not a digit, and "hello123".isalpha() is also False because it contains numbers.
print("123.45".isdigit())
print("hello123".isalpha())
# Output:
# False
# FalseUse these methods when the rule is simple. For more complicated validation, such as signed numbers or decimal values, use explicit parsing logic instead.
Finding text inside a string
Search methods help you check whether a piece of text appears in a string or where it appears. They are useful for prefixes, suffixes, and simple substring checks.
| Method | What it returns | Example |
|---|---|---|
| find() | Lowest index of the match, or -1 if not found. | "banana".find("na") → 2 |
| rfind() | Highest index of the match, or -1 if not found. | "banana".rfind("na") → 4 |
| index() | Lowest index of the match, or raises an error if not found. | "banana".index("na") → 2 |
| startswith() | True if the string begins with the given text. | "python".startswith("py") → True |
| endswith() | True if the string ends with the given text. | "notes.txt".endswith(".txt") → True |
find() is often safer than index() when the text may be missing, because it gives -1 instead of raising an exception.
Using find() and index()
Use find() when you want a testable result. Use index() when missing text is a bug and should stop the program.
message = "save the file"
print(message.find("file"))
print(message.startswith("save"))
# Output:
# 9
# TrueThese methods are common in parsing code because they are fast and easy to read. They do not use full regular expression matching; they simply compare text directly.
Splitting, joining, and breaking text into pieces
These methods are central to text processing. Use them when you need to turn one string into a list of pieces or combine a list into one string again.
| Method | What it does | Example |
|---|---|---|
| split() | Breaks a string into a list. | "a,b,c".split(",") → ["a", "b", "c"] |
| rsplit() | Splits from the right side first. | "a,b,c".rsplit(",", 1) → ["a,b", "c"] |
| splitlines() | Splits on line boundaries. | "a\nb\n".splitlines() → ["a", "b"] |
| join() | Combines an iterable of strings into one string. | ",".join(["a", "b", "c"]) → "a,b,c" |
split() and join() work together
split() turns one string into a list. join() does the opposite shape of work by taking many strings and combining them into one.
items = "red green blue".split()
result = " | ".join(items)
print(items)
print(result)
# Output:
# ['red', 'green', 'blue']
# red | green | blueUse join() with an iterable of strings. If the list contains a non-string item, Python raises an error because it cannot combine text with numbers directly.
Replacing and translating characters
These methods change specific pieces of text inside a string. They are useful for simple substitutions, formatting cleanup, and character-by-character transformations.
| Method | What it does | Example |
|---|---|---|
| replace() | Replaces one substring with another. | "I like cats".replace("cats", "dogs") → "I like dogs" |
| translate() | Replaces characters using a translation table. | "abc".translate(table) |
| maketrans() | Creates a translation table for translate(). | str.maketrans(...) |
Replacing text with a limit
The optional count argument lets you limit how many replacements happen. This is useful when only the first few matches should change.
text = "spam spam spam"
print(text.replace("spam", "eggs", 2))
# Output: eggs eggs spamreplace() is simple and readable for exact text. If you need patterns, optional parts, or flexible matching, regular expressions are a better fit than string methods.
Formatting strings with alignment and padding
These methods change how text is displayed. They are common when printing reports, labels, or small tables in the terminal.
| Method | What it does | Example |
|---|---|---|
| center() | Centers text in a field of a given width. | "hi".center(6) → " hi " |
| ljust() | Left-justifies text in a field. | "hi".ljust(5) → "hi " |
| rjust() | Right-justifies text in a field. | "hi".rjust(5) → " hi" |
| zfill() | Adds leading zeros before digits. | "42".zfill(5) → "00042" |
Using zfill() for numeric-looking text
zfill() is handy when you need fixed-width IDs, counters, or codes stored as text.
invoice_number = "58"
print(invoice_number.zfill(6))
# Output: 000058This method works on strings, not numbers. If you start with an integer, convert it first or use formatted strings.
Counting and measuring string content
These methods help you measure parts of a string or count how often text appears. They are useful in text analysis, data cleaning, and simple validation.
| Method | What it returns | Example |
|---|---|---|
| count() | How many times a substring appears. | "banana".count("na") → 2 |
| len() | The number of characters in the string. | len("banana") → 6 |
count() does not count overlapping matches. For example, "aaaa".count("aa") returns 2, not 3.
print("aaaa".count("aa"))
# Output: 2This matters when you are counting patterns in repeated text. If overlaps matter, you need a different approach.
Common mistakes when using Python string methods
Expecting string methods to change the original string
String methods return new values. The original string stays unchanged unless you assign the result to a variable.
Problem: This code calls upper() but ignores the returned string, so the variable still holds the old text.
name = "Maya"
name.upper()
print(name)
# Output: MayaFix: Store the result in the same variable or a new one.
name = "Maya"
name = name.upper()
print(name)
# Output: MAYAThe fixed version works because the returned string is assigned back to name.
Using strip() to remove a whole word
strip() removes individual characters from the ends, not a full substring. That is a common source of unexpected results.
Problem: This code tries to remove the exact prefix and suffix "ab", but strip() removes any matching a or b characters from both ends.
text = "abccba"
print(text.strip("ab"))
# Output: ccFix: Check the prefix and suffix explicitly, then slice them away if they are present.
text = "abccba"
if text.startswith("ab") and text.endswith("ba"):
text = text[2:-2]
print(text)
# Output: ccThe corrected version works because slicing removes an exact number of characters instead of treating the argument as a set of characters.
Calling join() on a list that is not all strings
join() expects every item to be a string. Beginners often forget to convert numbers first.
Problem: This code includes an integer in the list, so join() raises a type error instead of producing text.
parts = ["id", 42, "A"]
print("-".join(parts))
# TypeError: sequence item 1: expected str instance, int foundFix: Convert each item to a string before joining.
parts = ["id", 42, "A"]
text_parts = [str(part) for part in parts]
print("-".join(text_parts))
# Output: id-42-AThe corrected version works because join() receives only strings.
Predict the Output
What does this print after chaining methods?
text = " Python "
print(text.strip().lower())What does this print?
Show answer
strip() removes the spaces at both ends, leaving "Python". Then lower() changes that to "python".
# Output: pythonWhat happens when find() does not locate the text?
word = "banana"
print(word.find("z"))What does this print?
Show answer
find() returns -1 when the substring is not present. It does not raise an exception.
# Output: -1Try It Yourself
Write a small program that cleans up a username and checks whether it looks valid.
- Start with the string " Dev_User99 ".
- Remove leading and trailing whitespace.
- Convert the result to lowercase.
- Check whether the cleaned value contains only letters, digits, or underscores.
- Print the cleaned username and the validity check result.
Expected output:
dev_user99
TrueHint: Use strip(), lower(), and a small loop or all() with isalnum() logic. Remember that isalnum() does not allow underscores.
Show solution
username = " Dev_User99 "
cleaned = username.strip().lower()
is_valid = all(
char.isalnum() or char == "_"
for char in cleaned
)
print(cleaned)
print(is_valid)Summary
- Python string methods act on str objects and return new values.
- Use case methods such as upper(), lower(), title(), and swapcase() to normalize or display text.
- Use strip(), lstrip(), and rstrip() to remove unwanted characters from the ends of a string.
- Use search methods like find(), index(), startswith(), and endswith() to locate text.
- Use split(), join(), and replace() to reshape text and build new strings.
- Use validation methods such as isalpha() and isdigit() carefully, because they are stricter than many beginners expect.
Next, learn Python string slicing, which is the other core tool for working with text by position.