Text: working with strings
Join text, build messages with f-strings, and clean up text with upper(), lower(), strip() and replace() in Python, with a name-badge example.
🎯 By the end of this lesson you will be able to:
- Join strings and build messages with f-strings
- Use string methods to change case, trim spaces and replace text
- Find a string's length and pick out single characters
Outline
What you'll learn and why it matters
Names, emails, addresses, messages: a huge share of real data is text. Text in Python is called a string (a string of characters). In this lesson you will build friendly messages and clean up messy text, which is one of the most common jobs in real programs.
Joining strings
You can join (or concatenate) strings with +:
first = "Asha"
last = "Patel"
full_name = first + " " + last
print(full_name)Output
Asha Patel
Notice the " " in the middle: + joins text exactly, with nothing added, so you add the space yourself.
You cannot use + to join text and a number directly. Python stops, because it is not sure whether you want maths or text:
age = 25
print("Age: " + age)Python stops with this error
TypeError: can only concatenate str (not "int") to str
The fix is to turn the number into a string with str(), as in "Age: " + str(age), or, better, to use an f-string.
f-strings: the easy way to build messages
Put the letter f just before the opening quotation mark. Inside the string, anything in curly brackets { } is replaced by its value:
name = "Asha"
lessons_done = 4
print(f"Well done, {name}! You have finished {lessons_done} lessons.")Output
Well done, Asha! You have finished 4 lessons.
f-strings work with numbers and even calculations, and they can format numbers neatly. {price:.2f} shows a number with exactly 2 decimal places:
price = 531
quantity = 3
print(f"{quantity} books cost ₹{price * quantity:.2f}")Output
3 books cost ₹1593.00
String methods: cleaning up text
A method is a function that belongs to a value. You call it with a dot after the value: text.upper(). Strings come with many useful methods:
| Method | What it does | Example | Result |
|---|---|---|---|
upper() | ALL CAPITALS | "asha".upper() | "ASHA" |
lower() | all lowercase | "ASHA".lower() | "asha" |
title() | Capital First Letters | "asha patel".title() | "Asha Patel" |
strip() | Remove spaces at both ends | " hi ".strip() | "hi" |
replace(a, b) | Swap every a for b | "2025-09-01".replace("-", "/") | "2025/09/01" |
Methods do not change the original string; they give you a new one. To keep the result, store it in a variable:
raw_email = " Asha.Patel@Example.COM "
email = raw_email.strip().lower()
print(email)
print(raw_email)Output
asha.patel@example.com Asha.Patel@Example.COM
raw_email.strip().lower() runs from left to right: first strip() removes the spaces, then lower() makes the result lowercase. This is called chaining. The original raw_email is unchanged.
Length and single characters
len() tells you how many characters a string has. You can pick out one character with square brackets and its position, called its index. Python counts positions from 0, not 1:
word = "Python"
print(len(word))
print(word[0])
print(word[1])
print(word[-1])Output
6 P y n
word[0] is the first character and word[-1] is the last. Negative numbers count from the end.
Worked example: a name badge
A sign-up form gives you messy text. Turn it into a tidy badge.
raw_name = " meera NAIR "
raw_city = "kochi"
name = raw_name.strip().title()
city = raw_city.title()
initials = name[0] + name.split()[1][0]
print(f"Name: {name}")
print(f"City: {city}")
print(f"Initials: {initials}")
print(f"Badge length: {len(name)} characters")Output
Name: Meera Nair City: Kochi Initials: MN Badge length: 10 characters
The only new piece is name.split(), which breaks a string into a list of words at the spaces: ["Meera", "Nair"]. [1] takes the second word and [0] takes its first letter. You will learn lists properly in lesson 7.
Practice
Guided exercise
Clean a product code
A product code arrives as " sku-104-blue ". Print it in capitals with the spaces removed and the hyphens replaced by underscores: SKU_104_BLUE.
- Store the text in a variable
code. - Chain
strip(),upper()andreplace("-", "_"). - Print the result.
Show the solution
code = " sku-104-blue "
clean = code.strip().upper().replace("-", "_")
print(clean)Output
SKU_104_BLUE
How to get there: Each method returns a new string that the next method works on. The order of these three does not matter here, but strip() first is a good habit.
Your turn
Welcome message
Store name = "ravi" and course = "python for beginners". Use one f-string with title() to print Hi Ravi, welcome to Python For Beginners!.
Show the solution
name = "ravi"
course = "python for beginners"
print(f"Hi {name.title()}, welcome to {course.title()}!")Output
Hi Ravi, welcome to Python For Beginners!
How to get there: You can call methods inside the curly brackets of an f-string. title() capitalises the first letter of every word.
Common mistakes
Joining a string and a number with +
You see: TypeError: can only concatenate str (not "int") to str
Fix: Use an f-string, or wrap the number in str().
Forgetting the f before an f-string
You see: The braces appear in the output, e.g. Hi {name}
Fix: Put f directly before the opening quote: f"Hi {name}".
Expecting a method to change the variable
You see: name.upper() runs, but name is still lowercase
Fix: Store the result: name = name.upper().
Using an index that is too big
You see: IndexError: string index out of range
Fix: The last index is len(text) - 1. Use text[-1] for the last character.
Recap
- Strings are text in quotes. Join them with
+, or build messages with f-strings:f"Hi {name}". - Methods such as
strip(),lower(),title()andreplace()return a new string; store it to keep it. len()counts characters;text[0]is the first character andtext[-1]the last.- Use
{value:.2f}in an f-string to show a number with two decimal places.
Key terms
- Concatenate
- Join strings end to end.
- f-string
- A string starting with f that replaces {name} with the value of name.
- Method
- A function that belongs to a value, called with a dot, such as text.upper().
- Index
- The position of an item, counting from 0.
Check your understanding
Answer all 5 questions, then check your answers to see an explanation for each one.
1. What does this print? name = "sam" print(f"Hello {name.upper()}")
2. What is `"Python"[0]`?
3. You run `city = " Pune "` and then `city.strip()`. What is `city` now?
4. Why does `"Total: " + 50` cause an error?
5. What is `len("hi there")`?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.