How to work with strings
Create and combine strings
Python 3 strings contain Unicode text. Use matching single or double quotes, and use triple quotes for multiline text.
first = "Ada"
last = 'Lovelace'
full_name = first + " " + last
print(full_name)
Format with f-strings
Prefix a string with f to evaluate expressions inside braces. Format specifiers can control numbers and alignment.
name = "Ada"
score = 91.256
print(f"{name} scored {score:.1f}%")
Use methods
String methods return new strings because strings are immutable. Assign the result if you need to keep it.
raw = " Python Course "
clean = raw.strip().lower()
print(clean)
print(clean.replace("course", "lesson"))
Index and slice text
Indexes start at zero; negative indexes count from the end. A slice includes its start but excludes its stop.
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[1:4]) # yth
print("thon" in word)