Skip to content

Beginner · Text and decisions · topic 6 of 50 · 25 min

f-strings and string methods

Explanation

An f-string is a string with f before the quotes, where anything inside curly brackets {} is filled in with its value. String methods like upper(), strip(), replace() and split() give you a changed copy of the text. They never change the original string.

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

python
name = "Asha"
amount = 250
print(f"{name} paid Rs {amount}")
Shows Asha paid Rs 250. No str() needed: the f-string turns the number into text for you.
Think of it like this: An f-string is like a printed form with blanks: "Name: ____ Amount: ____". The curly brackets are the blanks, and Python fills each blank with the value of the variable you name.

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.

python
price = 40
qty = 3
print(f"{qty} plates cost Rs {price * qty}")
Shows 3 plates cost Rs 120.

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.

python
total = 1234.5
print(f"{total:.2f}")
big = 100000
print(f"{big:,}")
item = "Tea"
print(f"[{item:>10}]")
print(f"[{item:<10}]")
Shows 1234.50, then 100,000, then Tea pushed right and pushed left inside a 10-character space.
Tip: The :, spec uses the international style: 100000 becomes 100,000, not the Indian style 1,00,000. Python does not have Indian lakh grouping built in, so for lakhs and crores you need to write your own code.

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.

MethodWhat it gives backExampleResult
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
python
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"))
Methods can be chained: strip() first, then title() on the result. Shows Rahul Sharma, GOOD MORNING, 9876543210, 2 3 and True.

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.

python
line = "rice,dal,oil"
parts = line.split(",")
print(parts)
print(" | ".join(parts))
print("Best Chai in Pune".lower().split())
split(",") cuts at each comma. split() with nothing inside cuts at spaces. " | ".join(...) puts " | " between the pieces.
Careful: String methods return a NEW string. They never change the old one. Writing name.upper() on its own line does nothing useful. Store the result: name = name.upper().
python
name = "ravi"
name.upper()
print(name)
name = name.upper()
print(name)
The first print shows ravi (unchanged). Only after storing the result does it show RAVI.

Watch the lesson

f-strings and string methods · 1/7

f-strings and methods

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.

python
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:]}")
Shows Paid Rs 1,249.50 to Sharma General Store, From: Anjali Verma, UPI Ref: ...5432.

Practice (0/3 done)

Task 1 · Code · Python

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.

Task 2 · Code · Python

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

Task 3 · Code · Python

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

Question 1

1.If x = 3.14159, what does f"{x:.2f}" give?

Question 2

2.What does f"{100000:,}" give?

Question 3

3.name = "ravi", then the line name.upper(), then print(name). What is shown?

Question 4

4.What does "a,b,c".split(",") give?

Question 5

5.What does "banana".count("a") give?

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.

← Previous: Strings: working with text