String methods¶
In this tutorial, you will explore the most commonly used string methods in Python. These methods allow you to transform, split, join, and clean text with ease.
Time commitment: 15–20 minutes
Prerequisites:
- Completion of String basics
- Understanding of string indexing and slicing
Learning objectives¶
By the end of this tutorial, you will be able to:
- Use case conversion methods (
upper(),lower(),title(),capitalize(),swapcase()) - Split strings into lists with
split()andrsplit() - Join lists into strings with
join() - Remove whitespace with
strip(),lstrip(), andrstrip() - Replace substrings with
replace() - Chain multiple string methods together
Case conversion methods¶
Python provides several methods for changing the case of characters in a string. Because strings are immutable, each of these methods returns a new string rather than modifying the original.
str.upper() and str.lower()¶
The str.upper() method converts all characters to uppercase, and str.lower() converts all characters to lowercase. These are useful when you need to normalise text for comparison.
greeting = "Hello, World!"
print(greeting.upper())
print(greeting.lower())
str.title() and str.capitalize()¶
The str.title() method capitalises the first letter of every word in the string. The str.capitalize() method capitalises only the first character of the entire string and converts the rest to lowercase.
message = "string processing with python"
print(message.title())
print(message.capitalize())
str.swapcase()¶
The str.swapcase() method swaps the case of every character – uppercase becomes lowercase, and lowercase becomes uppercase.
mixed = "Hello, World!"
print(mixed.swapcase())
str.casefold() for case-insensitive comparisons¶
The str.casefold() method is similar to str.lower(), but it is more aggressive. It handles special characters from other languages that str.lower() does not convert. Use str.casefold() when you need reliable case-insensitive comparisons.
# The German lowercase letter sharp s
german_word = "Straße"
print(german_word.lower())
print(german_word.casefold())
# casefold is better for case-insensitive comparison
print("STRASSE".casefold() == "Straße".casefold())
Splitting strings¶
Splitting is one of the most common string operations. It allows you to break a string into a list of smaller strings based on a delimiter.
str.split() with no arguments¶
When you call str.split() without any arguments, it splits the string on any whitespace (spaces, tabs, and newlines) and automatically removes empty strings from the result.
sentence = " Python is great "
words = sentence.split()
print(words)
str.split(sep) with a delimiter¶
You can pass a specific separator to str.split(). When you do, it splits on that exact separator and does not remove empty strings.
csv_row = "Alice,Bob,,Charlie"
fields = csv_row.split(",")
print(fields)
str.split(sep, maxsplit) -- limiting the number of splits¶
The maxsplit parameter limits how many splits are performed. The remaining text stays in the last element of the list.
log_entry = "ERROR:2026-02-09:Something went wrong"
# Split into at most 2 parts
parts = log_entry.split(":", maxsplit=2)
print(parts)
str.rsplit() -- splitting from the right¶
The str.rsplit() method works like str.split(), but it splits from the right side of the string. This is particularly useful with maxsplit when you want to keep the beginning of the string intact.
file_path = "home/user/documents/report.txt"
# Split from the right to separate the filename from the directory
parts = file_path.rsplit("/", maxsplit=1)
print(parts)
str.splitlines() and str.partition()¶
The str.splitlines() method splits a string on line boundaries (including \n, \r\n, and \r). The str.partition() method splits a string into three parts: everything before the separator, the separator itself, and everything after.
multiline = "Line one\nLine two\nLine three"
lines = multiline.splitlines()
print(lines)
email = "user@example.com"
# partition splits into (before, separator, after)
local, separator, domain = email.partition("@")
print(f"Local part: {local}")
print(f"Domain: {domain}")
Joining strings¶
The str.join() method is the complement of str.split(). It takes a list (or any iterable) of strings and joins them together using the string as a separator.
words = ["Python", "is", "great"]
# Join with a space
sentence = " ".join(words)
print(sentence)
You can use any string as the separator, including an empty string, a comma, or a newline character.
letters = ["P", "y", "t", "h", "o", "n"]
# Join with no separator
print("".join(letters))
# Join with a comma and space
fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits))
# Join with a newline
lines = ["First line", "Second line", "Third line"]
print("\n".join(lines))
Combining split() and join() for text transformation¶
A common pattern is to split a string, process the parts, and then join them back together. This is a powerful technique for cleaning and transforming text.
messy_text = " too many spaces here "
# Normalise whitespace by splitting and rejoining
clean_text = " ".join(messy_text.split())
print(clean_text)
Stripping whitespace¶
User input and data from files often contain unwanted whitespace. Python provides three methods for removing it.
str.strip(), str.lstrip(), and str.rstrip()¶
The str.strip() method removes whitespace from both ends of a string. The str.lstrip() method removes whitespace from the left (start) only, and str.rstrip() removes it from the right (end) only.
padded = " Hello, World! "
print(repr(padded.strip()))
print(repr(padded.lstrip()))
print(repr(padded.rstrip()))
The repr() function is used here to show the exact string, including any remaining whitespace, by wrapping it in quotes.
Stripping specific characters¶
You can pass a string of characters to str.strip() to remove those specific characters instead of whitespace. Python removes any combination of the specified characters from the ends of the string.
url = "https://example.com/"
# Remove trailing slash
print(url.rstrip("/"))
# Remove surrounding punctuation
text = "***Important***"
print(text.strip("*"))
Replacing substrings¶
The str.replace() method returns a new string with all occurrences of a substring replaced by another substring.
message = "I like cats. Cats are wonderful."
# Replace all occurrences
new_message = message.replace("cats", "dogs")
print(new_message)
Notice that str.replace() is case-sensitive – it replaced "cats" but not "Cats". Keep this in mind when working with mixed-case text.
Limiting the number of replacements¶
You can pass a third argument to str.replace() to limit the number of replacements.
text = "one-two-three-four-five"
# Replace only the first two hyphens with spaces
result = text.replace("-", " ", 2)
print(result)
Method chaining¶
Because each string method returns a new string, you can chain multiple method calls together. This allows you to perform several transformations in a single expression.
raw_input = " Hello, World! "
# Strip whitespace, convert to lowercase, and replace the comma
cleaned = raw_input.strip().lower().replace(",", "")
print(cleaned)
Method chaining works because each method returns a new string, and the next method is called on that new string. You can read the chain from left to right:
strip()removes the leading and trailing whitespacelower()converts the result to lowercasereplace(",", "")removes the comma
Here is a practical example – creating a URL-friendly slug from a title.
title = " String Processing with Python! "
slug = title.strip().lower().replace(" ", "-").replace("!", "")
print(slug)
Exercises¶
Now it is time to practise what you have learned. Try to complete each exercise before looking at the solutions.
Exercise 1: Normalise a name¶
Given a name with inconsistent casing and extra whitespace, clean it up so that each word is capitalised and there is no leading or trailing whitespace.
For example, " alice SMITH " should become "Alice Smith".
name = " alice SMITH "
# Your solution here
Exercise 2: Build a CSV row¶
Given a list of values, join them into a comma-separated string. Then split the result back into a list to verify it matches the original.
For example, ["red", "green", "blue"] should produce "red,green,blue".
colours = ["red", "green", "blue"]
# Your solution here
Exercise 3: Clean up user input¶
Given a messy string from user input, perform the following steps:
- Strip leading and trailing whitespace
- Replace multiple spaces with a single space
- Convert everything to lowercase
For example, " Hello WORLD " should become "hello world".
user_input = " Hello WORLD "
# Your solution here
Exercise 4: Extract a file extension¶
Given a filename, use str.rsplit() to extract the file extension. Return the extension in lowercase without the dot.
For example, "Report.PDF" should produce "pdf".
filename = "Report.PDF"
# Your solution here
Solutions¶
Below are sample solutions for each exercise. Do not look at these until you have tried the exercises yourself!
# Solution 1: Normalise a name
name = " alice SMITH "
normalised_name = " ".join(name.split()).title()
print(normalised_name)
# Solution 2: Build a CSV row
colours = ["red", "green", "blue"]
csv_row = ",".join(colours)
print(csv_row)
# Verify by splitting it back
print(csv_row.split(",") == colours)
# Solution 3: Clean up user input
user_input = " Hello WORLD "
cleaned = " ".join(user_input.split()).lower()
print(cleaned)
# Solution 4: Extract a file extension
filename = "Report.PDF"
extension = filename.rsplit(".", maxsplit=1)[1].lower()
print(extension)
Summary¶
In this tutorial, you have learned about the most commonly used string methods in Python:
- Case conversion --
upper(),lower(),title(),capitalize(),swapcase(), andcasefold()allow you to change the case of characters - Splitting --
split(),rsplit(),splitlines(), andpartition()break strings into smaller parts - Joining --
join()combines a list of strings into a single string using a separator - Stripping --
strip(),lstrip(), andrstrip()remove unwanted characters from the ends of a string - Replacing --
replace()substitutes one substring for another - Method chaining -- you can call multiple methods in sequence because each method returns a new string
These methods form the foundation of text processing in Python. You will use them frequently in real-world projects.
In the next tutorial, String formatting, you will learn how to create well-formatted output using f-strings, str.format(), and the format specification mini-language.