String Methods in Python: A Beginner's Guide
Part of the series Python Basics — part 3
In Data Types in Python, we saw that a string is immutable: you can’t change a character inside it. So how do you change the case of a word, remove extra spaces or replace a piece of text? You use a string method, and each one returns a new string.
In this blog, we’ll go through the string methods one by one, grouped by what they are used for. Each method has a short explanation and an example.
If you are new to working with text in Python, these exercises cover the string basics that this blog builds on: Python Coding Exercise #54 (repeating a string), Python Coding Exercise #55 (comparing lengths), Python Coding Exercise #56 and Python Coding Exercise #57 (picking out characters by position) and Python Coding Exercise #59 (underlining a string).
What is a string method?
A method is a function that belongs to a value. For a string, you write the string (or a variable that holds it), then a dot, then the method name with brackets:
string.method(arguments)
Some methods need extra information inside the brackets, called arguments. Others, like upper(), need nothing.
course = "Intro to Python"
print(course.upper())
print(course)
Output:
INTRO TO PYTHON
Intro to Python
The first line shows the new, upper-case string. The second line shows that the original course hasn’t changed. This is what immutable means in practice: the method creates a new string and leaves the old one alone.
If you want to keep the new string, store it in a variable:
course = "Intro to Python"
loud_course = course.upper()
print(loud_course)
Output:
INTRO TO PYTHON
Python has 47 string methods, and this guide covers all of them, in groups:
| Group | Methods |
|---|---|
| Changing case | upper(), lower(), capitalize(), title(), swapcase(), casefold() |
| Trimming | strip(), lstrip(), rstrip(), removeprefix(), removesuffix() |
| Aligning and padding | ljust(), rjust(), center(), zfill(), expandtabs() |
| Searching and counting | count(), find(), rfind(), index(), rindex(), startswith(), endswith() |
| Replacing | replace(), maketrans(), translate() |
| Splitting and joining | split(), rsplit(), splitlines(), partition(), rpartition(), join() |
| Checking the content | isalpha(), isalnum(), isdigit(), isdecimal(), isnumeric(), isspace(), islower(), isupper(), istitle(), isidentifier(), isprintable(), isascii() |
| Formatting | format(), format_map() |
| Encoding | encode() |
Changing case
These methods return the same text with different capital letters.
upper()
Makes every letter upper case.
print("intro to python".upper())
Output:
INTRO TO PYTHON
lower()
Makes every letter lower case. It is useful when you want to compare text without worrying about capital letters. Python Coding Exercise #14 and Python Coding Exercise #35 both mention this trick.
print("INTRO TO PYTHON".lower())
answer = "Yes"
print(answer.lower() == "yes")
Output:
intro to python
True
capitalize()
Makes the first character upper case, and all the other letters lower case. It only looks at the start of the whole string, not at each word.
print("intro to PYTHON. level: beginner".capitalize())
Output:
Intro to python. level: beginner
title()
Makes the first letter of each word upper case, and the rest lower case.
print("intro to python".title())
Output:
Intro To Python
One thing to watch: title() treats an apostrophe as the end of a word, so the letter after it also becomes a capital.
print("don't stop".title())
Output:
Don'T Stop
swapcase()
Turns upper-case letters into lower case, and lower-case letters into upper case.
print("Intro to Python".swapcase())
Output:
iNTRO TO pYTHON
casefold()
Like lower(), but stronger. It is meant for comparing text, and it also handles letters from other languages that lower() leaves alone. For plain English text, lower() and casefold() give the same result.
word = "Straße"
print(word.lower())
print(word.casefold())
Output:
straße
strasse
Trimming
These methods remove characters from the edges of a string. By default, they remove whitespace: spaces, tabs and line breaks. The brackets in the examples below show where the string starts and ends.
strip()
Removes whitespace from both ends of a string. The spaces in the middle stay. Python Coding Exercise #23 uses .strip() as a safeguard for a number typed with a trailing space.
text = " hello world "
print(f"[{text}]")
print(f"[{text.strip()}]")
Output:
[ hello world ]
[hello world]
You can also give strip() a string of characters to remove instead of spaces. It removes any of those characters from both ends, until it reaches a different one.
print("***SALE***".strip("*"))
print("2026-10-25".strip("0123456789"))
Output:
SALE
-10-
lstrip()
Removes characters from the left end only (the beginning).
text = " hello world "
print(f"[{text.lstrip()}]")
Output:
[hello world ]
rstrip()
Removes characters from the right end only (the end).
text = " hello world "
print(f"[{text.rstrip()}]")
Output:
[ hello world]
removeprefix()
Removes a piece of text from the beginning of the string, but only if the string really starts with it. Otherwise, the string is returned unchanged. Unlike lstrip(), it removes the exact text you give, not a set of characters. It needs Python 3.9 or newer.
print("Mr. Anna".removeprefix("Mr. "))
print("Anna".removeprefix("Mr. "))
Output:
Anna
Anna
removesuffix()
The same idea for the end of the string.
print("report.csv".removesuffix(".csv"))
print("report.csv".removesuffix(".xlsx"))
Output:
report
report.csv
Aligning and padding
These methods add characters to a string until it reaches a width you choose. They are handy for printing neat columns.
ljust()
Left-aligns the string, and fills the rest of the width on the right. It takes the width, and optionally one fill character (a space by default).
print(f"[{'Python'.ljust(10)}]")
print("Python".ljust(10, "."))
Output:
[Python ]
Python....
rjust()
Right-aligns the string, and fills the rest of the width on the left. This is the method used in Python Coding Exercise #60.
print("Python".rjust(10, "*"))
Output:
****Python
If the string is already as long as the width, or longer, nothing is added and the string is returned as it is.
print("Python".rjust(3, "*"))
Output:
Python
The fill must be exactly one character. Anything else gives an error.
print("Python".rjust(10, "**"))
Output:
TypeError: The fill character must be exactly one character long
center()
Puts the string in the middle, and fills both sides. It is the method used in Python Coding Exercise #61, to print a word in the centre of a frame.
print("Python".center(12, "-"))
Output:
---Python---
zfill()
Fills the left side of the string with zeros until it reaches the width. It is commonly used for numbers like order numbers or time values. A minus or plus sign stays at the front.
print("42".zfill(5))
print("-42".zfill(5))
Output:
00042
-0042
expandtabs()
Replaces each tab character (\t) with spaces, so that the text lines up in columns of the size you choose. The default size is 8.
text = "name\tscore"
print(text.expandtabs(10))
print(text.expandtabs(4))
Output:
name score
name score
Searching and counting
These methods look inside a string. They are case-sensitive, so "A" and "a" are different.
count()
Counts how many times a piece of text appears. It counts matches that don’t overlap.
print("banana".count("a"))
print("banana".count("an"))
print("banana".count("x"))
Output:
3
2
0
find()
Returns the position (index) of the first match. The first character is at position 0. If the text isn’t found, it returns -1. You can also give a start position as a second argument.
print("banana".find("an"))
print("banana".find("x"))
print("banana".find("an", 2))
Output:
1
-1
3
rfind()
Like find(), but it returns the position of the last match.
print("banana".rfind("an"))
Output:
3
index()
Works like find(), with one difference: when the text isn’t found, it stops with an error instead of returning -1. Use it when the text is supposed to be there and a missing match would be a mistake.
print("banana".index("an"))
Output:
1
print("banana".index("x"))
Output:
ValueError: substring not found
rindex()
Like index(), but it returns the position of the last match.
print("banana".rindex("a"))
Output:
5
startswith()
Returns True if the string begins with the text you give, and False if not. You can also give several options in a tuple, and it returns True if the string starts with any of them.
course = "Intro to Python"
print(course.startswith("Intro"))
print(course.startswith("Python"))
print(course.startswith(("Advanced", "Intro")))
Output:
True
False
True
endswith()
Returns True if the string ends with the text you give.
filename = "report.csv"
print(filename.endswith(".csv"))
print(filename.endswith(".xlsx"))
Output:
True
False
To simply check whether some text appears anywhere inside a string, you don’t need a method. Use the in operator:
print("Python" in "Intro to Python")
Output:
True
Replacing
replace()
Returns a new string where every copy of one piece of text is swapped for another. A third argument limits how many replacements are made, counting from the left.
print("Intro to Python".replace("Python", "Java"))
print("banana".replace("a", "o"))
print("banana".replace("a", "o", 2))
Output:
Intro to Java
bonono
bonona
maketrans() and translate()
These two work together. maketrans() builds a translation table that says which character becomes which, and translate() uses that table to rebuild the string. It is a quick way to replace many single characters in one go.
maketrans() is called on str itself, not on a particular string. With two strings of the same length, each character in the first is replaced by the character in the same position in the second.
table = str.maketrans("abc", "xyz")
print("aabbcc".translate(table))
Output:
xxyyzz
A third argument to maketrans() lists characters to delete.
no_vowels = str.maketrans("", "", "aeiou")
print("education".translate(no_vowels))
Output:
dctn
Splitting and joining
split()
Cuts a string into pieces and returns them as a list. Give it a separator, and it cuts wherever that separator appears. The pieces are collected in a list, which is explained in Core Data Structures in Python.
print("Python,SQL,Excel".split(","))
Output:
['Python', 'SQL', 'Excel']
With no argument, split() cuts at any run of whitespace, and ignores extra spaces.
print("intro to python".split())
Output:
['intro', 'to', 'python']
A second argument sets the maximum number of cuts.
print("a-b-c-d".split("-", 1))
Output:
['a', 'b-c-d']
rsplit()
Like split(), but it counts the cuts from the right. The difference only shows when you limit the number of cuts.
print("a-b-c-d".rsplit("-", 1))
Output:
['a-b-c', 'd']
splitlines()
Cuts a string at its line breaks, and returns a list of lines.
text = "line one\nline two\nline three"
print(text.splitlines())
Output:
['line one', 'line two', 'line three']
partition()
Cuts a string at the first match of a separator, and always returns a tuple of three parts: the text before, the separator, and the text after. If the separator isn’t found, you get the whole string followed by two empty strings.
print("name=Anna".partition("="))
print("no separator here".partition("="))
Output:
('name', '=', 'Anna')
('no separator here', '', '')
rpartition()
Like partition(), but it cuts at the last match.
print("folder/sub/report.txt".rpartition("/"))
Output:
('folder/sub', '/', 'report.txt')
join()
The opposite of split(). It is called on the string you want between the items, and it joins the items of a list (or any collection of strings) into one string.
skills = ["Python", "SQL", "Excel"]
print(", ".join(skills))
print("-".join(skills))
Output:
Python, SQL, Excel
Python-SQL-Excel
All the items must be strings. A number in the list gives an error, so convert it with str() first.
print(", ".join(["Python", 3]))
Output:
TypeError: sequence item 1: expected str instance, int found
Checking the content
These methods answer a yes-or-no question about the string, so they return True or False. Most of them return False for an empty string.
isalpha()
True if every character is a letter, and the string isn’t empty.
print("Python".isalpha())
print("Python3".isalpha())
print("".isalpha())
Output:
True
False
False
isalnum()
True if every character is a letter or a number. Spaces and symbols make it False.
print("Python3".isalnum())
print("Python 3".isalnum())
Output:
True
False
isdigit(), isdecimal() and isnumeric()
These three check whether a string is made of number characters, and they only differ for unusual characters. For ordinary digits, such as 123, all three return True.
isdecimal()is the strictest. It accepts only the characters that make up normal decimal numbers, such as0to9.isdigit()also accepts digits like the superscript².isnumeric()is the widest. It also accepts things like the fraction½.
A decimal point is not a digit in any of them, so "3.5" is False for all three.
for text in ["123", "²", "½", "3.5"]:
print(text, text.isdecimal(), text.isdigit(), text.isnumeric())
Output (isdecimal, isdigit, isnumeric):
123 True True True
² False True True
½ False False True
3.5 False False False
To check that text typed by a user can be turned into a whole number with int(), isdecimal() is the safest choice, because it accepts only normal digits. (A negative number like -5 fails all three checks, because of the minus sign.)
isspace()
True if the string contains only whitespace (spaces, tabs or line breaks), and isn’t empty.
print(" ".isspace())
print(" a ".isspace())
print("".isspace())
Output:
True
False
False
islower() and isupper()
islower() is True if all the letters are lower case, and isupper() is True if all the letters are upper case. Characters that aren’t letters, such as numbers, are ignored, but there must be at least one letter.
print("python3".islower())
print("Python".islower())
print("PYTHON".isupper())
print("123".isupper())
Output:
True
False
True
False
istitle()
True if the string is in title case: each word starts with a capital letter, and the rest of its letters are lower case.
print("Intro To Python".istitle())
print("Intro to Python".istitle())
Output:
True
False
isidentifier()
True if the string could be used as a name in Python, such as a variable name. It must use letters, numbers or underscores, and it can’t start with a number.
print("total_sales".isidentifier())
print("2fast".isidentifier())
print("my-var".isidentifier())
Output:
True
False
False
isprintable()
True if every character can be printed on the screen. Characters like the line break (\n) and the tab (\t) are not printable.
print("Hello".isprintable())
print("Hello\n".isprintable())
Output:
True
False
isascii()
True if every character is in the basic ASCII set, which covers the English letters, numbers and common symbols. Letters with accents are outside it.
print("Hello".isascii())
print("Café".isascii())
Output:
True
False
Formatting
format()
Puts values into the {} placeholders of a string, in order. You can also add a format after a colon, such as .2f for two decimal places. There is also a built-in format() function for a single value, which is explained in Built-in Functions in Python.
print("{} has {} students".format("Intro to Python", 30))
print("The price is {:.2f}".format(3.14159))
Output:
Intro to Python has 30 students
The price is 3.14
Today, most people use f-strings for this, as shown in Data Types in Python and Python Coding Exercise #04, because they are shorter. format() is still common in older code.
format_map()
Like format(), but the values come from a dictionary, and the placeholders use the dictionary’s keys.
book = {"title": "Pachinko", "author": "Min Jin Lee"}
print("{title} by {author}".format_map(book))
Output:
Pachinko by Min Jin Lee
Encoding
encode()
Converts a string into bytes, using an encoding such as "utf-8", which is the default. You need this when you save text to a file or send it over a network. The result is a bytes value, which is a different type from a string.
data = "Café".encode("utf-8")
print(data)
print(type(data))
print(data.decode("utf-8"))
Output:
b'Caf\xc3\xa9'
<class 'bytes'>
Café
A string can only be encoded with an encoding that supports all of its characters. The basic "ascii" encoding has no é, so it gives an error.
print("Café".encode("ascii"))
Output:
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)
Using methods together
Since every method returns a new string, you can call another method on the result straight away. This is called chaining, and Python runs the methods from left to right.
raw = " intro TO python "
clean = raw.strip().title()
print(f"[{clean}]")
Output:
[Intro To Python]
This is useful for cleaning text typed by a user, as in name = input("Name: ").strip().title().
Comparing text without caring about case
Strings are compared exactly. The == operator treats "cat", "Cat" and "CAT" as three different strings, because the capital letters are different characters. That can be a problem when you ask the user a question, since people type the same answer in different ways.
The fix is to change the text to one case before comparing it. lower() is the usual choice. Whether the user types cat, Cat or CAT, the result is cat:
for answer in ["cat", "Cat", "CAT"]:
print(answer, answer == "cat", answer.lower() == "cat")
Output (the original answer, a direct comparison, and a comparison after lower()):
cat True True
Cat False True
CAT False True
The direct comparison fails for Cat and CAT, but after lower(), all three match. upper() works just as well, as long as both sides use the same one, for example answer.upper() == "CAT".
Extra spaces cause the same kind of problem, so the two fixes are often chained together:
answer = " Cat "
print(answer.strip().lower() == "cat")
Output:
True
For text in other languages, casefold() is the safer choice, as shown earlier. You can see the effect of exact comparison in Python Coding Exercise #37, where huey doesn’t match "Huey".
Which method do I need?
| I want to… | Use |
|---|---|
| Change to upper or lower case | upper(), lower() |
| Compare text regardless of capital letters | lower() on both sides |
| Capitalise the first letter of every word | title() |
| Remove extra spaces from the edges | strip() |
| Remove a known start or end from a string | removeprefix(), removesuffix() |
| Pad a string to a fixed width | ljust(), rjust(), center(), zfill() |
| Count how often something appears | count() |
| Find where something is | find() |
| Check how a string starts or ends | startswith(), endswith() |
| Swap some text for other text | replace() |
| Cut a string into a list | split(), splitlines() |
| Join a list into one string | join() |
| Check whether a string is all letters or digits | isalpha(), isdigit() |
| Put values into a template | format() or an f-string |
Key takeaways
- A string method is called with a dot:
string.method(). - Strings are immutable, so every method returns a new string and leaves the original unchanged. Store the result if you want to keep it.
upper(),lower(),title(),capitalize(),swapcase()andcasefold()change the case.strip(),lstrip()andrstrip()remove characters from the edges, andremoveprefix()andremovesuffix()remove an exact start or end.ljust(),rjust(),center()andzfill()pad a string to a width.find()returns-1when there is no match, butindex()stops with an error.split()turns a string into a list, andjoin()turns a list back into a string.- The
is...()methods returnTrueorFalse. - Methods can be chained:
text.strip().title().
Where to find the full list
This guide covers every string method in Python. For a quick reference list, see the W3Schools Python String Methods reference, and for the complete official description, see the Python documentation on string methods. For the built-in functions that work with strings and other values, such as len(), sorted() and format(), read Built-in Functions in Python.
✦ Thanks for reading! ✦