Python for beginners · Lesson 4 of 15

Strings: working with text

Create strings with quotes, join them, build text with f-strings, pick letters with indexes and slices, and use common string methods.

About 16 minutes · code runs in your browser, nothing to install

A string (str) is a piece of text: a name, a sentence, an address, even a single letter. You write it between double quotes or single quotes. If the text itself contains double quotes, wrap it in single quotes, and the other way round.

Pythoneditable
greeting = "Hello"
place = 'world'
quote = 'She said "hi" and left.'
print(greeting, place)
print(quote)
Output
Hello world
She said "hi" and left.

Joining strings

+ glues two strings together (this is called concatenation) and * repeats a string. You cannot add a number to a string directly: turn the number into text first with str().

Pythoneditable
first = "Ana"
last = "Silva"
full = first + " " + last
print(full)
print("-" * 12)
age = 34
print(full + " is " + str(age))
Output
Ana Silva
------------
Ana Silva is 34

f-strings: the easy way to build text

Put an f right before the opening quote, and you can drop variables and even calculations into the text inside curly braces {}. Add :.2f after a number to show it with exactly 2 decimals, which is ideal for money.

Pythoneditable
name = "Lena"
items = 3
total = 19.5
print(f"{name} bought {items} items.")
print(f"Total: {total:.2f} euros")
print(f"Per item: {total / items:.2f} euros")
Output
Lena bought 3 items.
Total: 19.50 euros
Per item: 6.50 euros

Indexing and slicing

Each character in a string has a position number, called an index, starting at 0. word[0] is the first character and word[-1] the last. A slice word[start:end] gives the characters from start up to, but not including, end. len() counts the characters.

Pythoneditable
word = "Python"
print(len(word))
print(word[0])
print(word[1])
print(word[-1])
print(word[0:2])
print(word[2:])
print(word[:3])
print(word[-3:])
Output
6
P
y
n
Py
thon
Pyt
hon

Leave out the start of a slice to begin at 0, or the end to go to the last character.

Common string methods

A method is a function that belongs to a value; you call it with a dot: text.upper(). Strings have many useful ones: str.strip() removes spaces at both ends, str.upper() and str.lower() change the case, str.replace() swaps text, str.find() gives the index where some text starts, and str.title() capitalises each word. The keyword in checks whether one string appears inside another.

Pythoneditable
text = "  Hello, Python learners!  "
clean = text.strip()
print(clean)
print(clean.upper())
print(clean.lower())
print(clean.replace("Python", "new"))
print(clean.startswith("Hello"))
print(clean.count("l"))
print(clean.find("Python"))
print("Python" in clean)
print("ana silva".title())
print(len(text), len(clean))
Output
Hello, Python learners!
HELLO, PYTHON LEARNERS!
hello, python learners!
Hello, new learners!
True
3
7
True
Ana Silva
27 23
Note: Strings never change. Methods like upper() or strip() return a new string and leave the original alone: text above still has its spaces. To keep the result, store it in a variable, as with clean.

✎ Exercise

The variable full holds a messy name. Clean it so it prints as Maria Garcia, print its length, then print the initials using indexes, as Initials: MG.

Hint: Chain strip() and title(). The second initial is the character right after the space, so use find(" ") + 1 as the index.

Your codewrite your answer, then Run
full = "  maria garcia  "
# your code here

Expected output:

Maria Garcia
12
Initials: MG
Show a solution
Solutioneditable
full = "  maria garcia  "
clean = full.strip().title()
space = clean.find(" ")
initials = clean[0] + clean[space + 1]
print(clean)
print(len(clean))
print(f"Initials: {initials}")
Output
Maria Garcia
12
Initials: MG

Check yourself

1. What is "Python"[1]?

2. What does "ab" * 3 give?

3. After name = "ana" and name.upper(), what does print(name) show?

Spotted a mistake on this page? Tell us