Beginner · Text and decisions · topic 6 of 50 · 25 min
f-strings and string methods
Explanation
f-strings: filling in the blanks
An f-string is a string with the letter f just before the opening quote. Inside it, you put a variable name in curly brackets {}. Python replaces the brackets with the value. The f stands for "formatted".
name = "Asha"
amount = 250
print(f"{name} paid Rs {amount}")You can also put a small calculation, called an expression, inside the brackets. Python works it out first and puts the answer in the text.
price = 40
qty = 3
print(f"{qty} plates cost Rs {price * qty}")Format specs: controlling how values look
After the value, inside the brackets, you can add a colon and a format spec. A format spec is a short instruction for how the value should look. :.2f means "a decimal number with exactly 2 digits after the point". :, puts commas between thousands. :>10 makes the text 10 characters wide and pushes it to the right.
total = 1234.5
print(f"{total:.2f}")
big = 100000
print(f"{big:,}")
item = "Tea"
print(f"[{item:>10}]")
print(f"[{item:<10}]")String methods
A method is a function that belongs to a value. You call it with a dot after the value: name.upper(). Strings come with many useful methods.
| Method | What it gives back | Example | Result |
|---|---|---|---|
| upper() | all capital letters | "chai".upper() | "CHAI" |
| lower() | all small letters | "CHAI".lower() | "chai" |
| title() | first letter of each word capital | "ravi kumar".title() | "Ravi Kumar" |
| strip() | spaces removed from both ends | " hi ".strip() | "hi" |
| replace(a, b) | every a changed to b | "1-2-3".replace("-", "/") | "1/2/3" |
| find(x) | index of the first x, or -1 | "banana".find("n") | 2 |
| count(x) | how many times x appears | "banana".count("a") | 3 |
| startswith(x) / endswith(x) | True or False | "Mr Rao".startswith("Mr") | True |
raw = " rAHUL sharma "
print(raw.strip().title())
print("good morning".upper())
print("9876-543-210".replace("-", ""))
print("banana".find("n"), "banana".count("a"))
print("priya@gmail.com".endswith("@gmail.com"))split and join
split() cuts a string into pieces and gives back a list. A list is a group of values inside square brackets; you will learn lists fully in a later module. join() does the opposite: it glues pieces together with the string you call it on.
line = "rice,dal,oil"
parts = line.split(",")
print(parts)
print(" | ".join(parts))
print("Best Chai in Pune".lower().split())name = "ravi"
name.upper()
print(name)
name = name.upper()
print(name)Watch the lesson
f-strings and string methods · 1/7
In this lesson you will learn f-strings, the easiest way to put values inside text, and the most useful string methods.
Prefer a video by a teacher? Find free videos on “python f-strings and string methods tutorial for beginners” on YouTube ↗
In real life: A UPI payment receipt
After Anjali pays a shop with UPI, the app shows a neat receipt: the amount with commas and two decimals, the shop name, and only the last four digits of the reference number. f-strings with format specs make this in a few lines.
payer = "anjali verma"
shop = "Sharma General Store"
amount = 1249.5
ref = "412398765432"
print(f"Paid Rs {amount:,.2f} to {shop}")
print(f"From: {payer.title()}")
print(f"UPI Ref: ...{ref[-4:]}")Practice (0/3 done)
Write a function receipt(name, amount) that returns text like "Asha paid Rs 250.00", always with 2 digits after the decimal point. Use an f-string.
People type their names in messy ways. Write a function clean_name(raw) that removes spaces from both ends and makes the first letter of each word capital. Example: clean_name(" rAHUL sharma ") returns "Rahul Sharma".
Write a function make_slug(title) that turns a title into a web address part: all small letters, words joined with "-". Extra spaces must not create empty parts. Example: make_slug("Best Chai in Pune") returns "best-chai-in-pune".
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.