Strings and f-strings: working with text
Create, slice and change text with f-strings and the most useful string methods, and learn why strings are immutable.
In this lesson you will
- Create strings and use escape sequences
- Build text with f-strings and formatting
- Index and slice strings
- Use essential string methods
About 18 minutes
Text is everywhere
Names, messages, headlines, search boxes, error notices: most of what people read on a screen is text. In Python, text is called a string, a row of characters strung together like beads. Learning to handle strings well is one of the most useful skills a beginner can pick up, because nearly every real program reads, builds or cleans text.
Creating strings
single = 'Single quotes'
double = "Double quotes"
quote = "She said 'hello'" # mix to include the other kind
apostrophe = "It's fine"
multi = """Line one
Line two
Line three"""
print(single)
print(quote)
print(multi)
Single quotes
She said 'hello'
Line one
Line two
Line three
Single and double quotes are identical. Triple quotes let a string span several lines. A backslash \ inside a string is an escape: \n means a new line, \t a tab, and \" a quote character.
print("Line one\nLine two")
print("Name:\tSara")
print("She said \"hello\"")
print(r"C:\new\table") # raw string: backslashes stay as typed
Line one
Line two
Name: Sara
She said "hello"
C:\new\table
f-strings: the best way to build text
Joining text with + gets messy fast. An f-string, a string with an f before the opening quote, lets you drop values straight into the sentence with curly brackets.
name = "Sara"
items = 3
price = 120
print("Hi " + name + ", you have " + str(items) + " items.") # the old, clumsy way
print(f"Hi {name}, you have {items} items.") # the f-string way
print(f"Total: Rs {items * price}") # any expression works
Hi Sara, you have 3 items.
Hi Sara, you have 3 items.
Total: Rs 360
Formatting controls come after a colon inside the brackets. These are used constantly for prices, percentages and tidy tables.
price = 1234.5
ratio = 0.256
n = 7
print(f"{price:.2f}") # 2 decimals
print(f"{price:,.2f}") # with thousands separator
print(f"{ratio:.1%}") # as a percentage
print(f"{n:03}") # pad with zeros: 007
print(f"{'left':<8}|{'right':>8}|{'mid':^8}|") # align
1234.50
1,234.50
25.6%
007
left | right| mid |
Length, positions and slicing
word = "Python"
print(len(word)) # 6
print(word[0]) # P (counting starts at 0!)
print(word[3]) # h
print(word[-1]) # n (last character)
print(word[0:2]) # Py (from 0 up to, not including, 2)
print(word[2:]) # thon (from 2 to the end)
print(word[:3]) # Pyt (from the start up to 3)
print(word[::-1]) # nohtyP (reversed!)
6
P
h
n
Py
thon
Pyt
nohtyP
Computers count from zero. The first character is at position 0, the second at 1, and so on. Negative numbers count from the end: -1 is the last character. A slice [start:stop] includes the start but stops before the stop position. This feels odd for a day or two, then becomes natural.
Useful string methods
A method is an action that belongs to a value, called with a dot: value.method(). Strings have dozens. These are the ones you will use most.
| Method | What it does | Example result |
|---|---|---|
upper() / lower() |
Change case | "Hi".upper() gives 'HI' |
title() |
Capitalise Each Word | "learn python".title() gives 'Learn Python' |
strip() |
Remove spaces at both ends | " hi ".strip() gives 'hi' |
replace(a, b) |
Swap text | "a-b".replace("-", " ") gives 'a b' |
split(sep) |
Break into a list | "a,b,c".split(",") gives ['a', 'b', 'c'] |
join(list) |
Glue a list together | "-".join(["a","b"]) gives 'a-b' |
find(x) |
Position of x, or -1 | "cat".find("t") gives 2 |
startswith(x) / endswith(x) |
Check the beginning or end | "cat".startswith("c") gives True |
count(x) |
How many times | "banana".count("a") gives 3 |
isdigit() |
Only digits? | "123".isdigit() gives True |
raw = " Sara.Khan@Example.COM "
clean = raw.strip().lower()
print(clean)
print(clean.replace(".", " "))
print(clean.split("@"))
print("example" in clean) # the in keyword checks for text inside
print(clean.count("a"))
words = ["Learn", "Python", "today"]
print(" ".join(words))
print("-".join(words).upper())
sara.khan@example.com
sara khan@example com
['sara.khan', 'example.com']
True
4
Learn Python today
LEARN-PYTHON-TODAY
Strings never change
word = "hello"
word.upper() # makes a new string, but we threw it away
print(word) # still hello
word = word.upper() # keep the new string
print(word)
hello
HELLO
Strings are immutable, which means a method never changes the original. It hands you a new string. If you want to keep it, store it in a variable.
word = "hello"
word[0] = "J"
Traceback (most recent call last):
...
TypeError: 'str' object does not support item assignment
Instead, build a new string: "J" + word[1:] gives "Jello".
Looping over text
word = "Python"
for letter in word:
print(letter, end=" ")
print()
vowels = 0
for ch in "Learning Python is fun":
if ch.lower() in "aeiou":
vowels += 1
print("Vowels:", vowels)
P y t h o n
Vowels: 6
Turn the sentence " learn python in minutes " into a title-case version without the extra spaces, then print how many letters it has (use len).
Show one possible answer
text = " learn python in minutes "
tidy = text.strip().title()
print(tidy)
print(len(tidy))
Learn Python In Minutes
23
Given a full name in the form "khan, sara", print it as Sara Khan using split, strip and title.
Hint: split(‘,’) gives two pieces you can unpack into two variables.
Show one possible answer
full = "khan, sara"
last, first = full.split(",")
print(f"{first.strip().title()} {last.strip().title()}")
Sara Khan
Mixing up positions: the last character of a string of length 6 is at position 5, not 6. Asking for word[6] raises an IndexError. Use word[-1] when you want the last one.
You do not need to memorise every method. Type help(str) in the shell, or search for “Python string methods”, whenever you need one. Professionals do this daily.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does "Python"[0] return?
- ‘y’
- ‘n’
- ‘P’
- An error
Counting starts at zero.
What does "Python"[-1] return?
- ‘P’
- ‘o’
- An error
- ‘n’
Negative positions count from the end.
Which builds a sentence with a variable inside?
"Hi {name}"f"Hi {name}""Hi" - nameprint.Hi(name)
An f before the quote makes it an f-string.
What does "a,b,c".split(",") return?
- ‘abc’
- 3
- [‘a’, ‘b’, ‘c’]
- (‘a’,’b’,’c’)
split breaks text into a list.
Why does word.upper() not change word?
- Strings are immutable; the method returns a new string
- upper is broken
- word is a number
- You need print
Store the result in a variable.
Summary
- f-strings are the best way to build text.
- Positions start at 0; negative positions count from the end.
- Slices [start:stop] stop before stop.
- String methods return new strings.
Questions
Single or double quotes?
No difference. Pick one style and stay consistent, switching only to avoid escaping.
What is a docstring?
A triple-quoted string placed first inside a function or file to describe it. You will meet it in the functions lesson.
How do I check whether a string is empty?
Use if not text:, since an empty string counts as False.
