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 spansmultiple lines."""Common string methods
Section titled “Common string methods”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")) # Trueprint(s.endswith("! ")) # Trueprint(len(s)) # 18Methods return new strings — they never modify the original.
Slicing
Section titled “Slicing”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]) # Helloprint(s[7:]) # Python!print(s[-7:]) # Python!print(s[::-1]) # !nohtyP ,olleH (reversed)print(s[::2]) # Hlo,Pto!f-strings (formatted string literals)
Section titled “f-strings (formatted string literals)”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 = 30pi = 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().
join() and split()
Section titled “join() and split()”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.
Full runnable demo
Section titled “Full runnable demo”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 = 30pi = 3.14159print(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}")Loading Python runtime (first run only)…