String Methods
Beginner Python Basics

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.

GoalBy the end you can clean, split, search, pad and reformat text with string methods, chain them together, and explain why you must store the result.

Before this lesson: Python Strings

2String Methods: diagram

Python String MethodsOriginal string (never changes)raw = " Blue Sky! "len(raw) -> 13New string returnedclean = raw.strip().lower()clean -> "blue sky!".strip().lower()
A method never edits the string it is called on. It builds a fresh string, so you assign the result to a name, and chained methods pass each new string to the next call.

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.

Python
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.

Python
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.

Python
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().

Python
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.

Python
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.

Python
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().

Python
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.

Python
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.

Python
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

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.

Interactive example
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.

  1. Line 1A messy CSV-like line: extra spaces, odd capital letters and a trailing newline \n.
  2. Line 3strip() removes the leading spaces and the newline from both ends of the line.
  3. Line 4split(",") cuts at commas into three parts, and the list comprehension strips the spaces around each part. The three values are unpacked into names.
  4. Line 6-7title() fixes the capitals, turning "maya RAO" into "Maya Rao" (the double space inside stays) and "new delhi" into "New Delhi".
  5. Line 9-10isdigit() confirms the age text is only digits before int() converts it, so bad data would be skipped instead of crashing.
  6. Line 12The cleaned values are printed with | separators.
  7. Line 13Chaining lower() and replace() builds a lowercase username from the name.
  8. Line 14zfill(5) pads "29" with zeros to width 5, giving "00029".
  9. Line 15startswith("New") is True and find("Delhi") returns the position 4.

8String Methods: common mistakes

Forgetting to store the result

✗ Wrong

name = "asha"
name.upper()
print(name)
Prints asha: strings are immutable, so the new string was thrown away

✓ 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)
Prints ['red', '', 'green', '', '', 'blue'] with empty strings

✓ 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("@")
ValueError: substring not found

✓ 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))
TypeError: sequence item 0: expected str instance, int found

✓ 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"))
Prints an empty string: every b, a and n at the start was removed

✓ 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

Write 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".

Your code
def clean_name(raw):
    pass

2. Predict the string methods

Predict the output Easy

Type exactly what this program prints. Watch out for repr() quotes, the partition tuple and what find() returns when nothing matches.

Read this code
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"))

2 more exercises → 6 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

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