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.
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.
greeting = "Hello"
place = 'world'
quote = 'She said "hi" and left.'
print(greeting, place)
print(quote)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().
first = "Ana"
last = "Silva"
full = first + " " + last
print(full)
print("-" * 12)
age = 34
print(full + " is " + str(age))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.
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")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.
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:])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.
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))Hello, Python learners! HELLO, PYTHON LEARNERS! hello, python learners! Hello, new learners! True 3 7 True Ana Silva 27 23
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.
full = " maria garcia "
# your code here
Expected output:
Maria Garcia 12 Initials: MG
Show a solution
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}")Maria Garcia 12 Initials: MG
Check yourself
1. What is "Python"[1]?
Indexes start at 0, so index 1 is the second character, y.
2. What does "ab" * 3 give?
* repeats a string the given number of times.
3. After name = "ana" and name.upper(), what does print(name) show?
upper() returns a new string but does not change name. You would need name = name.upper().