Build and format text with f-strings, slice and index characters, and use the most common string methods to clean and search text.
Why: a string is text. You can wrap it in single or double quotes — pick one and be consistent. Triple quotes span multiple lines.
single = 'hello'
double = "hello" # identical to single quotes
# use the other quote style to include a quote inside
quote = "She said 'hi'"
multiline = """Line one
Line two"""
print(multiline)Why: an f-string is the modern way to drop values into text. Put an f before the quote, then wrap any variable or expression in curly braces. It is shorter and clearer than gluing strings with +.
name = 'Ada'
age = 30
print(f'{name} is {age} years old') # Ada is 30 years old
print(f'Next year: {age + 1}') # Next year: 31
print(f'{3.14159:.2f}') # 3.14 (2 decimal places)Why: each character has a position (index) starting at 0. Negative indexes count from the end. Slicing [start:stop] grabs a range — the stop position is not included.
word = 'Python'
print(word[0]) # 'P' (first character)
print(word[-1]) # 'n' (last character)
print(word[0:3]) # 'Pyt' (positions 0, 1, 2)
print(word[3:]) # 'hon' (from 3 to the end)
print(len(word)) # 6 (how many characters)Why: strings come with built-in tools. A method is a function attached to a value — you call it with a dot. Strings never change in place; these return a new string.
text = ' Hello, World '
print(text.strip()) # 'Hello, World' (trim whitespace)
print(text.lower()) # ' hello, world '
print(text.replace('l', 'L'))# ' HeLLo, WorLd '
print('a,b,c'.split(',')) # ['a', 'b', 'c'] (text -> list)
print('-'.join(['a', 'b'])) # 'a-b' (list -> text)
print('Hello'.startswith('He')) # True