Python String Methods
String Methods
Python strings come with a rich collection of built-in methods that let you analyze, modify, format, and validate text. A method is a function that belongs to an object and is called using dot notation:
result = text.method_name(arguments)
For example, "hello".upper() calls the upper() method on the string "hello".
Important: Strings in Python are immutable — they cannot be changed after they are created. Every string method that "modifies" text actually returns a new string and leaves the original unchanged.
name = "python"
upper_name = name.upper()
print(name)
print(upper_name)
Expected output:
python
PYTHON
If you want to keep the result, assign it to a variable — either a new one or the same one (name = name.upper()).
This lesson groups the most commonly used string methods by purpose, with examples and expected output for each.
Case Conversion Methods
These methods change the uppercase and lowercase letters in a string.
capitalize()
Makes the first character of the string uppercase and the rest lowercase.
text = "python programming"
print(text.capitalize())
Expected output:
Python programming
Note that only the first character of the whole string is capitalized, not the first character of each word.
lower() and upper()
Convert all characters to lowercase or uppercase.
name = "PyThOn"
print(name.lower())
print(name.upper())
Expected output:
python
PYTHON
Practical use — case-insensitive comparison:
user_answer = "YES"
if user_answer.lower() == "yes":
print("Confirmed")
Expected output:
Confirmed
Converting both sides to the same case means "Yes", "YES", and "yes" are all accepted.
swapcase()
Switches uppercase letters to lowercase and lowercase letters to uppercase.
word = "Hello WORLD"
print(word.swapcase())
Expected output:
hELLO world
title()
Capitalizes the first letter of each word.
sentence = "welcome to python"
print(sentence.title())
Expected output:
Welcome To Python
Caution:
title()treats any non-letter as a word boundary, so"they're"becomes"They'Re". It works best for simple text.
Searching and Counting Methods
These methods help you locate text inside a string.
count()
Returns how many times a substring appears in the string.
msg = "banana apple banana"
print(msg.count("banana"))
Expected output:
2
find() and rfind()
Return the index (position) where a substring is found.
find()searches from the left and returns the first match.rfind()searches from the right and returns the last match.- Both return
-1if the substring is not found.
text = "learn python easily"
print(text.find("python"))
print(text.rfind("e"))
print(text.find("java"))
Expected output:
6
13
-1
Explanation:
"python"starts at index 6 (indexes start at 0, and the space afterlearnis index 5).- The last
ein the string is at index 13, the start ofeasily. "java"does not appear, sofind()returns-1.
index() and rindex()
Work like find() and rfind(), but raise a ValueError if the substring is not found, instead of returning -1.
word = "developer"
print(word.index("v"))
print(word.rindex("e"))
Expected output:
2
7
If the substring is missing:
word = "developer"
print(word.index("z"))
Output:
ValueError: substring not found
When to use which: use find() when a missing value is a normal situation you will check for; use index() when the value must exist and a missing value indicates an error.
Trimming and Alignment Methods
strip(), lstrip(), and rstrip()
Remove whitespace (spaces, tabs, and newlines) from the edges of a string.
| Method | Removes Whitespace From |
|---|---|
strip() | Both ends |
lstrip() | The left (start) only |
rstrip() | The right (end) only |
data = " Python "
print("[" + data.strip() + "]")
print("[" + data.lstrip() + "]")
print("[" + data.rstrip() + "]")
Expected output:
[Python]
[Python ]
[ Python]
The square brackets make the remaining spaces visible.
You can also pass specific characters to remove:
price = "$$$250$$"
print(price.strip("$"))
Expected output:
250
center(), ljust(), and rjust()
Align text within a given total width. An optional second argument sets the fill character (a space by default).
title = "Menu"
print(title.center(20, "-"))
print(title.ljust(20, "."))
print(title.rjust(20, "."))
Expected output:
--------Menu--------
Menu................
................Menu
Each result is exactly 20 characters long. These methods are useful for creating simple text tables and headings in console programs.
Splitting and Joining Methods
split() and rsplit()
Split a string into a list of substrings, using a separator.
languages = "Python,Java,C++"
print(languages.split(","))
Expected output:
['Python', 'Java', 'C++']
An optional maxsplit argument limits how many splits are made. rsplit() performs the splits starting from the right:
path = "home/user/docs/file.txt"
print(path.split("/", 1))
print(path.rsplit("/", 1))
Expected output:
['home', 'user/docs/file.txt']
['home/user/docs', 'file.txt']
join()
Joins the items of a list (or any iterable of strings) into a single string. The string you call join() on becomes the separator.
items = ["2026", "01", "03"]
print("-".join(items))
Expected output:
2026-01-03
join() is the reverse of split(). All items must be strings; "-".join([1, 2]) raises a TypeError.
splitlines()
Splits text at line breaks.
lines = "Line1\nLine2\nLine3"
print(lines.splitlines())
Expected output:
['Line1', 'Line2', 'Line3']
This is useful when processing text read from a file.
Validation and Checking Methods
These methods return True or False. They are commonly used to validate user input.
isalnum(), isalpha(), and isdigit()
| Method | Returns True If All Characters Are |
|---|---|
isalnum() | Letters or digits |
isalpha() | Letters only |
isdigit() | Digits only |
print("Python3".isalnum())
print("Python".isalpha())
print("12345".isdigit())
Expected output:
True
True
True
Watch out for these cases:
print("Hello World".isalpha()) # Contains a space
print("12.5".isdigit()) # Contains a decimal point
print("".isalpha()) # Empty string
Expected output:
False
False
False
All of these methods return False for an empty string.
islower() and isupper()
Check whether all cased letters are lowercase or uppercase.
print("hello".islower())
print("HELLO".isupper())
Expected output:
True
True
isspace() and isprintable()
isspace()returnsTrueif the string contains only whitespace.isprintable()returnsTrueif all characters are printable. Characters like\n(newline) are not printable.
print(" ".isspace())
print("Hello\n".isprintable())
Expected output:
True
False
startswith() and endswith()
Check how a string begins or ends.
file = "report.pdf"
print(file.startswith("report"))
print(file.endswith(".pdf"))
Expected output:
True
True
You can pass a tuple to check several options at once:
file = "report.pdf"
print(file.endswith((".pdf", ".docx")))
Expected output:
True
Practical Example: Validating a PIN
pin = "4821"
if len(pin) == 4 and pin.isdigit():
print("Valid PIN")
else:
print("PIN must be exactly 4 digits")
Expected output:
Valid PIN
Replacement and Translation Methods
replace()
Replaces occurrences of a substring with another substring.
sentence = "I like Java"
print(sentence.replace("Java", "Python"))
Expected output:
I like Python
An optional third argument limits the number of replacements:
print("banana".replace("a", "o", 1))
Expected output:
bonana
partition() and rpartition()
Split a string into exactly three parts: the text before the separator, the separator itself, and the text after it. The result is a tuple.
email = "user@example.com"
print(email.partition("@"))
Expected output:
('user', '@', 'example.com')
rpartition() splits at the last occurrence of the separator:
filename = "archive.backup.zip"
print(filename.rpartition("."))
Expected output:
('archive.backup', '.', 'zip')
maketrans() and translate()
Replace multiple individual characters at once. First, str.maketrans() builds a translation table that maps characters to replacements; then translate() applies it.
table = str.maketrans("aeiou", "12345")
text = "education"
print(text.translate(table))
Expected output:
2d5c1t34n
Each vowel is replaced by the character in the same position of the second string: a→1, e→2, i→3, o→4, u→5.
removeprefix() and removesuffix()
Available since Python 3.9, these methods remove a specific prefix or suffix if it is present.
print("data.csv".removesuffix(".csv"))
print("Mr. Ravi".removeprefix("Mr. "))
Expected output:
data
Ravi
Unlike strip(), which removes any of the given characters, these remove an exact substring.
Formatting and Padding Methods
format() and format_map()
Insert values into placeholders {} in a string.
template = "Hello {}, welcome!"
print(template.format("Suriya"))
Expected output:
Hello Suriya, welcome!
Placeholders can also be named:
print("{name} is {age} years old".format(name="Asha", age=25))
Expected output:
Asha is 25 years old
format_map() takes the values from a dictionary:
person = {"name": "Asha", "age": 25}
print("{name} is {age} years old".format_map(person))
Expected output:
Asha is 25 years old
In modern Python, f-strings are usually preferred for formatting, but format() is still useful when the template is stored separately from the values.
zfill()
Pads a string on the left with zeros until it reaches the given width.
order_id = "45"
print(order_id.zfill(5))
Expected output:
00045
zfill() is aware of signs, so "-45".zfill(5) returns "-0045". It is useful for IDs, invoice numbers, and time values.
Quick Reference
| Category | Methods |
|---|---|
| Case conversion | capitalize(), lower(), upper(), swapcase(), title(), casefold() |
| Searching and counting | count(), find(), rfind(), index(), rindex() |
| Trimming and alignment | strip(), lstrip(), rstrip(), center(), ljust(), rjust() |
| Splitting and joining | split(), rsplit(), splitlines(), join() |
| Validation | isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), isprintable(), startswith(), endswith() |
| Replacement | replace(), partition(), rpartition(), maketrans(), translate(), removeprefix(), removesuffix() |
| Formatting and padding | format(), format_map(), zfill() |
Practical Example: Cleaning User Input
Methods can be chained, because each one returns a new string:
raw_email = " Asha.Kumar@Example.COM "
clean_email = raw_email.strip().lower()
print(clean_email)
print(clean_email.endswith("@example.com"))
Expected output:
asha.kumar@example.com
True
strip() runs first and returns a trimmed string; lower() is then called on that result.
Common Mistakes
- Not saving the result:
name.strip()on its own line does nothing useful. Writename = name.strip(). - Confusing
find()andindex():find()returns-1when the text is missing;index()raises an error. - Using
isdigit()for decimal numbers:"12.5".isdigit()isFalse. Usetry/exceptwithfloat()instead. - Calling
join()on the list: it is"-".join(items), notitems.join("-"). - Expecting
strip("abc")to remove the word"abc": it removes any combination of the charactersa,b, andcfrom the ends. Useremoveprefix()/removesuffix()for exact text.
Related Concepts
- Python Strings — creating, indexing, and slicing strings
- Python Formatting Strings — f-strings and format specifiers
- Python Lists — the result type of
split()and the input tojoin() - Python RegEx — advanced pattern-based searching and replacing