Tutorials › Python Tutorial › Python String Methods and f-strings

Python String Methods and f-strings

12 min read · Lesson 8 of 24

A method is a function that belongs to a value. You call it with a dot: value.method(). Strings come with dozens of handy methods for cleaning, searching and reshaping text. This lesson covers the ones you will use every week, plus f-strings, the modern way to build text from variables.

Changing case

Example PYTHON
name = "aMiNa wAMBUi"
print(name.upper())
print(name.lower())
print(name.title())
print(name.capitalize())
print(name.swapcase())
Result
AMINA WAMBUI
amina wambui
Amina Wambui
Amina wambui
AmInA WambuI
Try it Yourself »
Note: Each method returns a new string. The original name is unchanged, because strings are immutable (see Python Strings).

Removing extra spaces

Text typed by users often has stray spaces at the start or end. strip() removes them. lstrip() and rstrip() clean only the left or right side.

Example PYTHON
raw = "   0722 000 111   "
print("[" + raw.strip() + "]")
print("[" + raw.lstrip() + "]")
print("[" + raw.rstrip() + "]")
Result
[0722 000 111]
[0722 000 111   ]
[   0722 000 111]
Try it Yourself »

Replacing text

replace(old, new) swaps every occurrence of one piece of text for another.

Example PYTHON
phone = "0722 000 111"
print(phone.replace(" ", ""))
greeting = "Good morning, Nairobi"
print(greeting.replace("Nairobi", "Nakuru"))
Result
0722000111
Good morning, Nakuru
Try it Yourself »

Searching

MethodWhat it returns
find(x)index of the first x, or -1 if not found
index(x)like find(), but raises an error if not found
count(x)how many times x appears
startswith(x)True if the string starts with x
endswith(x)True if the string ends with x
Example PYTHON
email = "[email protected]"
print(email.find("@"))
print(email.count("o"))
print(email.startswith("otieno"))
print(email.endswith(".co.ke"))
print(email.find("#"))
Result
6
4
True
True
-1
Try it Yourself »

Splitting and joining

split() breaks a string into a list of parts. With no argument it splits on whitespace; you can also give a separator. join() does the opposite: it glues a list of strings together using the string it is called on.

Example PYTHON
line = "Kisumu,Siaya,Homa Bay,Migori"
counties = line.split(",")
print(counties)
print(len(counties))
print(" | ".join(counties))
Result
['Kisumu', 'Siaya', 'Homa Bay', 'Migori']
4
Kisumu | Siaya | Homa Bay | Migori
Try it Yourself »

Checking what a string contains

Methods starting with is return True or False:

Example PYTHON
print("2024".isdigit())
print("Mombasa".isalpha())
print("Mombasa 1".isalpha())
print("hello".islower())
Result
True
True
False
True
Try it Yourself »

These are useful for validating data, for example checking that an ID number contains only digits.

f-strings

An f-string is a string with the letter f before the opening quote. Inside it, anything in curly braces { } is evaluated and inserted into the text. This is the cleanest way to mix text and values.

Example PYTHON
name = "Mercy"
items = 3
price = 120
print(f"{name} bought {items} items for KES {items * price}.")
Result
Mercy bought 3 items for KES 360.
Try it Yourself »

You can put any expression inside the braces, including method calls: f"{name.upper()}".

Formatting numbers

After the expression, a colon starts a format specifier that controls how the value looks.

Example PYTHON
total = 1234567.891
rate = 0.1575
print(f"Total: KES {total:,.2f}")
print(f"Rate: {rate:.1%}")
print(f"Rounded: {total:.0f}")
Result
Total: KES 1,234,567.89
Rate: 15.8%
Rounded: 1234568
Try it Yourself »
SpecifierEffect
.2f2 decimal places
,thousands separator
.1%percentage with 1 decimal
>10right-align in 10 characters
<10left-align in 10 characters
^10centre in 10 characters

Aligning text in columns

Alignment specifiers make neat tables in plain text:

Example PYTHON
print(f"{'Item':<10}{'Price':>8}")
print(f"{'Milk':<10}{65:>8}")
print(f"{'Bread':<10}{70:>8}")
print(f"{'Eggs':<10}{450:>8}")
Result
Item         Price
Milk            65
Bread           70
Eggs           450
Try it Yourself »
Tip: Since Python 3.8 you can write f"{x=}" to print both the variable name and its value, for example x=5. It is a quick debugging aid.

Exercises

Exercise

Make the text uppercase.

print("nanyuki".())
Exercise

Complete the f-string so it prints "Karibu, Juma!".

name = "Juma"
print("Karibu, {name}!")

Next: Python Booleans and Operators.

Sign in or create a free account to track progress, earn XP, badges and a certificate.