Python String Methods
1String Methods: overview
A string method is a built-in function called on text with a dot, such as text.strip() or text.split(), that returns a new string, list or value without changing the original.
Before this lesson: Python Strings
2String Methods: diagram
3String Methods: explained step by step
A string method is a function that belongs to a piece of text and is called with a dot: name.upper(). Python has dozens of them, and together they cover most text work: cleaning user input, splitting lines of data, searching, padding and formatting. This page goes beyond the basics in Python strings and groups the methods by the job they do.
Methods return new strings
Strings are immutable, so no method can change the text it is called on. Each one returns a new string (or a number, boolean or list) and leaves the original alone. If you do not store the result, it is lost.
title = " python basics "
title.upper()
print(repr(title))
title = title.strip().upper()
print(repr(title))The first call computed " PYTHON BASICS " and threw it away. Assigning the result back, as in the second call, is how you "change" a string.
Changing letter case
Five methods change case. lower() and upper() are the workhorses for comparing text without caring about capitals, title() capitalises every word, capitalize() only the first letter of the whole string, and swapcase() flips each letter.
text = "hELLO wORLD"
print(text.lower())
print(text.upper())
print(text.title())
print(text.capitalize())
print(text.swapcase())
print("Straße".casefold() == "STRASSE".casefold())casefold() is a stronger lower() meant for comparisons, and it handles letters such as the German ß. Use it when users may type text in any language.
Removing whitespace and unwanted characters
strip() removes whitespace (spaces, tabs, newlines) from both ends; lstrip() and rstrip() handle one side. Give them a string and they remove any of those characters instead. Nothing in the middle is touched.
line = " total: 42\n"
print(repr(line.strip()))
print(repr(line.rstrip()))
print("***sale***".strip("*"))
print("2024-report.txt".removesuffix(".txt"))Careful: strip("abc") removes any mix of a, b and c, not the word "abc". For a fixed prefix or suffix use removeprefix() and removesuffix().
Splitting text into pieces and joining it back
split() breaks a string into a list. With no argument it splits on any run of whitespace and ignores extra spaces. With an argument it splits exactly on that separator, so doubled separators produce empty strings. rsplit() splits from the right, splitlines() splits on line breaks, and join() is the opposite of split().
sentence = " red green blue "
print(sentence.split())
print(sentence.split(" "))
print("2024-05-17".split("-"))
print("a=b=c".rsplit("=", 1))
print("line one\nline two".splitlines())
print(" / ".join(["Mon", "Tue", "Wed"]))join() is called on the separator, and every item must already be a string. This is the reason "-".join(numbers) fails until you convert with str(); see Python casting.
Replacing text
replace(old, new) swaps every occurrence. An optional third argument limits how many replacements happen.
phone = "555-123-4567"
print(phone.replace("-", ""))
print(phone.replace("-", " ", 1))
print("a,b;c".replace(",", ";").split(";"))Searching: find, index, count and startswith
find() returns the position of the first match or -1. index() does the same but raises a ValueError when nothing matches, which is the right choice when a missing piece means the data is broken. count() counts non-overlapping matches, rfind() searches from the right, and startswith() / endswith() accept a tuple of options.
email = "maya@example.com"
print(email.find("@"))
print(email.find("#"))
print(email.count("a"))
print(email.endswith((".com", ".org")))
print("report.final.csv".rfind("."))
try:
email.index("#")
except ValueError as error:
print("ValueError:", error)You can combine find() with slicing to cut text around a position. For anything more pattern-like, such as "digits followed by a dash", reach for regular expressions.
Checking what a string contains
The is... methods return True or False and are handy for validating input. They require at least one character, so an empty string is never isdigit().
print("2024".isdigit(), "20.5".isdigit())
print("Asha".isalpha(), "Asha7".isalpha(), "Asha7".isalnum())
print(" ".isspace(), "".isspace())
print("hello".islower(), "Hello".istitle())Note that "20.5".isdigit() is False because of the dot. To validate decimals, try float() inside try/except instead.
Padding, aligning and splitting in three
zfill(width) pads numbers with zeros, ljust, rjust and center pad with spaces (or any one character you pass), and partition(sep) splits at the first separator into exactly three parts: before, separator, after. That fixed shape makes it perfect for key=value lines.
print("42".zfill(5))
print("Item".ljust(8, ".") + "$5".rjust(5))
print("menu".center(12, "-"))
print("theme=dark=blue".partition("="))
key, _, value = "volume=7".partition("=")
print(key, value)For richer layouts, f-strings can align text too: f"{name:<8}{price:>6}".
Chaining methods and a real example
Because each method returns a string, you can chain calls left to right. A classic use is building a URL slug from a title.
title = " 10 Tips: Clean Python Code! "
slug = title.strip().lower().replace(":", "").replace("!", "").replace(" ", "-")
print(slug)
table = str.maketrans("", "", ":!?,.")
print(title.strip().lower().translate(table).replace(" ", "-"))str.maketrans() and translate() replace or delete many single characters in one pass, which is neater than a long chain of replace() calls.
Quick reference: String Methods
- Python String Cheat Sheet: Methods and Formatting — Python strings are immutable text: use slicing to cut them, methods such as `upper()`, `strip()`, `split()` a…
- Python Regex Cheat Sheet (re Module Quick Reference) — Python regular expressions live in the `re` module: write the pattern as a raw string, then use `re.search()`…
- How to Reverse a String in Python — Use slicing: `text[::-1]` returns a new string with the characters in reverse order. `"".join(reversed(text))…
- How to Check if a String Contains a Substring in Python — Use the `in` operator: `"cat" in "concatenate"` returns `True` if the substring appears anywhere in the strin…
- How to Convert a List to a String in Python — Use `", ".join(items)` to glue a list of strings into one string. If the list holds numbers, convert them fir…
- How to Remove Whitespace from a String in Python — Use `text.strip()` to remove whitespace from both ends, or `"".join(text.split())` to remove it everywhere, i…
- How to Convert a String to a List in Python — Use `text.split()` to get a list of words, `text.split(",")` to split on a separator, or `list(text)` to get …
- How to Split a String into Words in Python — Call `text.split()` with no arguments: it splits on any whitespace and returns a list of words, such as `"to …
4String Methods: syntax
text.lower() text.upper() text.title() # case
text.strip() text.strip("chars") # trim ends
text.split(sep) sep.join(parts) # split / join
text.replace(old, new, count)
text.find(sub) text.index(sub) text.count(sub)
text.startswith(prefix) text.endswith((a, b))
text.isdigit() text.isalpha() text.isalnum()
text.zfill(5) text.ljust(8) text.rjust(8) text.center(8)
text.partition(sep)
5String Methods: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
raw_line = " maya RAO , 29 , new delhi \n"
line = raw_line.strip()
name, age, city = [part.strip() for part in line.split(",")]
name = name.title()
city = city.title()
if age.isdigit():
age = int(age)
print(name, "|", age, "|", city)
print(name.lower().replace(" ", "."))
print("ID-" + str(age).zfill(5))
print(city.startswith("New"), city.find("Delhi"))Expected outputMaya Rao | 29 | New Delhi
maya..rao
ID-00029
True 4
7String Methods: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1A messy CSV-like line: extra spaces, odd capital letters and a trailing newline
\n. - Line 3
strip()removes the leading spaces and the newline from both ends of the line. - Line 4
split(",")cuts at commas into three parts, and the list comprehension strips the spaces around each part. The three values are unpacked into names. - Line 6-7
title()fixes the capitals, turning"maya RAO"into"Maya Rao"(the double space inside stays) and"new delhi"into"New Delhi". - Line 9-10
isdigit()confirms the age text is only digits beforeint()converts it, so bad data would be skipped instead of crashing. - Line 12The cleaned values are printed with
|separators. - Line 13Chaining
lower()andreplace()builds a lowercase username from the name. - Line 14
zfill(5)pads"29"with zeros to width 5, giving"00029". - Line 15
startswith("New")isTrueandfind("Delhi")returns the position4.
8String Methods: common mistakes
Forgetting to store the result
✗ Wrong
name = "asha"
name.upper()
print(name)✓ Right
name = "asha"
name = name.upper()
print(name)Assign the returned value back: name = name.upper().
Using split(" ") on messy spaces
✗ Wrong
words = "red green blue".split(" ")
print(words)✓ Right
words = "red green blue".split()
print(words)Call split() with no argument to split on any run of whitespace.
Using index() when the text may be missing
✗ Wrong
email = "maya.example.com"
position = email.index("@")✓ Right
email = "maya.example.com"
position = email.find("@")
if position == -1:
print("No @ found")Use find() and check for -1, or catch the ValueError.
Joining numbers without converting them
✗ Wrong
numbers = [1, 2, 3]
print("-".join(numbers))✓ Right
numbers = [1, 2, 3]
print("-".join(str(n) for n in numbers))join() needs strings. Convert each item with str().
Thinking strip("abc") removes a word
✗ Wrong
print("banana".lstrip("ban"))✓ Right
print("banana".removeprefix("ban"))strip() removes any of the listed characters. To drop a fixed prefix use removeprefix().
9String Methods: exercises
Write your answer, then press Check. The checks run in your browser.
1. Tidy a typed name
Write code Easy ✓ CompletedWrite a function clean_name(raw) that returns the name with spaces removed from both ends, repeated inner spaces collapsed to one, and each word capitalised. Example: " mAYA rao " becomes "Maya Rao".
def clean_name(raw):
pass
def clean_name(raw):
return " ".join(raw.split()).title()
2. Predict the string methods
Predict the output Easy ✓ CompletedType exactly what this program prints. Watch out for repr() quotes, the partition tuple and what find() returns when nothing matches.
text = " Data,Science,Python "
print(text.strip().split(","))
print("a-b-c".replace("-", "", 1))
print("report.final.csv".rpartition(".")[2])
print("42".zfill(5), "7".rjust(3, "*"))
print("hello".find("z"), "hello".count("l"))['Data', 'Science', 'Python']
ab-c
csv
00042 **7
-1 2
2 more exercises → 6 more examples
Questions learners ask
Why doesn't text.upper() change my variable?
Strings are immutable, so a method cannot modify the original text. It returns a new string. Write text = text.upper() to keep the result. The same rule applies to strip(), replace() and every other string method.
What is the difference between find() and index()?
Both return the position of the first match. When the text is missing, find() returns -1 while index() raises a ValueError. Use find() when absence is normal, and index() when it should be treated as an error.
What is the difference between split() and split(' ')?
split() with no argument treats any run of spaces, tabs and newlines as one separator and drops empty pieces. split(' ') cuts at every single space, so two spaces in a row give an empty string in the result. See Python strings for more basics.
Further reading
10Next lesson
Up nextPython f-StringsAn f-string is a string literal starting with f whose {braces} hold Python expressions and optional format specs, so va…Related:
Python StringsPython f-StringsPython List MethodsPython Slicing
← Python Strings · All Python Basics lessons · Practise in the IDE