Skip to content

Strings

Strings are sequences of Unicode characters

Section titled “Strings are sequences of Unicode characters”

Python 3 strings (str) are immutable sequences of Unicode code points. Single quotes and double quotes are interchangeable — choose one and be consistent. Triple quotes (""" or ''') allow multi-line strings.

a = "Hello"
b = 'World'
c = """This spans
multiple lines."""

Strings ship with dozens of methods. These are the ones you will use constantly:

s = " Hello, Python! "
print(s.strip()) # "Hello, Python!"
print(s.upper()) # " HELLO, PYTHON! "
print(s.lower()) # " hello, python! "
print(s.replace("Python", "World")) # " Hello, World! "
print(s.startswith(" H")) # True
print(s.endswith("! ")) # True
print(len(s)) # 18

Methods return new strings — they never modify the original.

Strings support the same slicing syntax as lists: s[start:stop:step]. Negative indices count from the end.

s = "Hello, Python!"
print(s[0:5]) # Hello
print(s[7:]) # Python!
print(s[-7:]) # Python!
print(s[::-1]) # !nohtyP ,olleH (reversed)
print(s[::2]) # Hlo,Pto!

f-strings, introduced in Python 3.6, are the standard way to embed expressions in strings. Prefix the string with f and place any Python expression inside {}.

name = "Alice"
age = 30
pi = 3.14159
print(f"Name: {name}, Age: {age}")
print(f"Pi to 2dp: {pi:.2f}")
print(f"2 + 2 = {2 + 2}")
print(f"Upper: {name.upper()}")

Format specifiers after : control alignment, precision, and type — the same mini-language used by str.format().

str.split(sep) breaks a string into a list. sep.join(iterable) joins a list of strings into one. They are inverses of each other.

csv = "one,two,three,four"
parts = csv.split(",") # ['one', 'two', 'three', 'four']
rejoined = " | ".join(parts) # 'one | two | three | four'
print(parts)
print(rejoined)

Always join with a string method (", ".join(items)), never concatenate in a loop — loop concatenation creates O(n²) intermediate strings.

s = "Hello, Python!"
print(s.upper())
print(s.lower())
print(s.replace("Python", "World"))
print(s.startswith("Hello"))
print(len(s))
print(s[0:5])
print(s[-7:])
print(s[::2])
name = "Alice"
age = 30
pi = 3.14159
print(f"Name: {name}, Age: {age}")
print(f"Pi to 2dp: {pi:.2f}")
words = ["one", "two", "three"]
joined = ", ".join(words)
print(joined)
parts = "a:b:c:d".split(":")
print(parts)
try:
s[0] = "h"
except TypeError as e:
print(f"TypeError: {e}")
What does `"Hello, World!"[7:]` return?
Which method is the idiomatic way to concatenate a list of strings?
What does the `f` prefix in `f"Hello {name}"` do?
Why are strings described as immutable in Python?