fuckingpython.lol

Learn Python › Lesson 3

Python strings: slicing, f-strings and other shit you do to text

Updated · every example run on Python 3.9 to 3.15

Most of what a program shoves around is text: names, messages, menu items, the error that just ruined your evening. In Python a piece of text is a string, type str, which you met in lesson 2. This lesson is everything you can do to one: make it, glue it, poke at single letters, chop it into pieces, and the error you get the first time you mix text with a number.

Single, double or triple quotes

A string is text between quotes. Single and double quotes make exactly the same string, so pick whichever lets you put the other kind inside without drama:

main.py
order = "Large pizza"
note = 'extra cheese'
review = "It's the best pizza in town"
menu = 'The menu says "world famous"'
toppings = "pepperoni\nmushrooms"
address = """12 Main Street
Apartment 4B
Ring twice, the bell is broken"""

print(order)
print(note)
print(review)
print(menu)
print(toppings)
print(address)
Python 3.9 to 3.15 all print
Large pizza
extra cheese
It's the best pizza in town
The menu says "world famous"
pepperoni
mushrooms
12 Main Street
Apartment 4B
Ring twice, the bell is broken

The \n in toppings is a backslash escape: two characters in your code, one new line in the string. \t is a tab and \\ is a single backslash. Three quotes in a row, """ or ''', let a string run over several lines, new lines included.

Forget the closing quote and Python stops before running a single line. Python 3.9 calls it "EOL while scanning string literal", which is robot for "the line ended and the string didn't". From 3.10 on it says "unterminated string literal" and names the line. It is a close cousin of the bracket that was never closed.

Gluing with + and repeating with *

+ between two strings glues them into a new one. * with a whole number repeats a string that many times:

main.py
size = "large"
pizza = "pepperoni"
order = size + " " + pizza
print(order)
print("Yum" + "!" * 5)
print("=" * 20)
Python 3.9 to 3.15 all print
large pepperoni
Yum!!!!!
====================

Notice the " " in the middle. print with commas puts spaces between things for you; + doesn't put a damn thing anywhere, so the space is your job. In "Yum" + "!" * 5 Python does the * before the +, the same order as in math, so the five exclamation marks get made first and then glued on.

f-strings: put variables inside text

Gluing with + gets ugly fast. The way you'll actually build text is an f-string: an f right before the opening quote, and anything inside {} gets run as Python and dropped into the text:

main.py
name = "Mittens"
age = 7
weight = 4.567
print(f"{name} is {age} years old")
print(f"Next year {name} will be {age + 1}")
print(f"{name} weighs {weight:.1f} kg")
print("{name} is {age} years old")
Python 3.9 to 3.15 all print
Mittens is 7 years old
Next year Mittens will be 8
Mittens weighs 4.6 kg
{name} is {age} years old

Numbers go in without any fuss, and the braces can hold a calculation, like age + 1. The :.1f after weight is a format spec: show this number with one digit after the decimal point. It only changes how the number is printed; weight itself is still 4.567.

The last line is the bug you'll write at least once this week. No f, so the braces are just characters, and Python prints them as they are, no error and no warning. f-strings have existed since Python 3.6, so every Python you'll meet has them.

len, indexing and slicing

len() counts the characters in a string, spaces included. Square brackets pull out one character by its position, and a colon inside the brackets pulls out a slice:

main.py
word = "pancakes"
print(len(word))
print(word[0])
print(word[1])
print(word[-1])
print(word[0:3])
print(word[3:])
print(word[:-1])
print(word[::-1])
Python 3.9 to 3.15 all print
8
p
a
s
pan
cakes
pancake
sekacnap

Positions start at 0, not 1. Yes, really. Negative positions count from the end, so -1 is always the last character:

 p  a  n  c  a  k  e  s
 0  1  2  3  4  5  6  7
-8 -7 -6 -5 -4 -3 -2 -1

A slice [start:stop] includes the start and stops just before the stop, which is why [0:3] is three characters. Leave out the start and it begins at the beginning; leave out the stop and it runs to the end. [:-1] is everything except the last character, and a third number is the step, so [::-1] walks backwards and hands you the word reversed.

One difference to remember: ask for a single position that doesn't exist, like word[20], and you get IndexError: string index out of range. A slice that runs past the end, like word[3:20], just gives you what's there and shuts up about it.

Methods, and why strings never change

A string comes with a toolbox of methods: functions that belong to it, called with a dot after the value. Here is a sloppy shopping list item getting cleaned up:

main.py
item = "  maple SYRUP  "
clean = item.strip().lower()
print(clean)
print(clean.upper())
print(clean.title())
print(clean.replace("maple", "pancake"))
print(clean.startswith("maple"))
print(clean.count("p"))
print(clean.find("syrup"))
print(f"[{item}]")
item[0] = "M"
Python 3.15 prints
maple syrup
MAPLE SYRUP
Maple Syrup
pancake syrup
True
2
6
[  maple SYRUP  ]
Traceback (most recent call last):
  File "/home/me/project/main.py", line 11, in <module>
    item[0] = "M"
    ~~~~^^^
TypeError: 'str' object does not support item assignment
PythonPrints
3.9–3.15TypeError: 'str' object does not support item assignment

Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.

strip() cuts spaces, tabs and new lines off both ends, lower(), upper() and title() change the capitals, replace() swaps one piece of text for another, startswith() answers True or False, count() counts how many times a piece of text appears, and find() tells you the position where the text starts (or -1 if it isn't there). item.strip().lower() chains two calls: strip first, then lowercase whatever strip handed back.

Now look at the line of output in square brackets. After all those methods, the original still has its spaces and its shouting. Every method handed back a new string and left the old one alone, because Python strings are immutable: once a string exists, nothing changes it. The last line tries anyway, and gets TypeError: 'str' object does not support item assignment.

So to "change" a string, you make a new one and move the name onto it: item = item.strip(). Calling item.strip() on a line by itself does the work and throws the result away, and you'll stare at your unchanged string wondering what the hell happened.

Break it: adding a number to a string

+ between two strings glues them. + between two numbers adds them. Between a string and a number, Python refuses to guess which one you meant:

main.py
age = 7
print("Mittens is " + age + " years old")
Python 3.15 prints
Traceback (most recent call last):
  File "/home/me/project/main.py", line 2, in <module>
    print("Mittens is " + age + " years old")
          ~~~~~~~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str
PythonPrints
3.9–3.15TypeError: can only concatenate str (not "int") to str

Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.

Every version from 3.9 to 3.15 words it the same: you can only concatenate (glue) a str to a str, and you handed it an int. Python 3.11 and later also point at the + that failed. Put the number first, as in 7 + " years", and the message changes to "unsupported operand type(s) for +: 'int' and 'str'", which is the same problem from the other side.

The fix is an f-string, f"Mittens is {age} years old", which turns the number into text for you. You can also convert it yourself with str(age); lesson 4 covers conversions properly. More on this error, including why input() walks you straight into it, on TypeError: can only concatenate str (not "int") to str.

Try it yourself

You have dish = " spaghetti BOLOGNESE ". Clean it up and print one line that looks like Today's special: Spaghetti Bolognese (19 characters), with the number coming from len(), not typed by hand.

Show the answer
dish = "  spaghetti BOLOGNESE "
clean = dish.strip().title()
print(f"Today's special: {clean} ({len(clean)} characters)")

len() counts the space in the middle too. Count it on dish instead of clean and the spaces at the ends sneak into the number.

Questions

How do I reverse a string in Python?

Slice it with a step of -1: text[::-1]. That walks the string backwards and gives you a new, reversed string.

What is an f-string in Python?

A string literal with an f before the opening quote, like f"{name} is {age}". Each expression in braces is evaluated and its value is put into the text. They have been in Python since version 3.6.

How do I change one character in a Python string?

You can't change it in place, because strings are immutable. Build a new string and assign it to the same name, for example word = "P" + word[1:], or use replace().

Is there a difference between single and double quotes in Python?

No. 'pizza' and "pizza" are the same string. Use double quotes when the text has an apostrophe in it and single quotes when it has double quotes in it.

Sources

Read on November 11, 2026.