Strings
A string (str) is an immutable sequence of Unicode characters. Strings are everywhere — names, messages, file contents, web pages — so Python gives them rich syntax: several quoting styles, escape sequences, indexing and slicing, and dozens of methods.
Creating strings
single = 'single quotes' double = "double quotes" mixed = "It's easy" quoted = 'She said "hi"' multi = """Line one Line two""" print(mixed) print(quoted) print(multi)
It's easy She said "hi" Line one Line two
Single and double quotes are interchangeable; pick the one that avoids escaping. Triple quotes (""" or ''') allow line breaks inside the string.
Escape sequences and raw strings
print("Tab:\tafter tab") print("New\nline") print("Backslash: \\") print("Unicode: caf\u00e9 \N{GREEK SMALL LETTER PI}") print(r"C:\new\table")
Tab: after tab New line Backslash: \ Unicode: café π C:\new\table
A r prefix makes a raw string, where backslashes are kept literally — essential for Windows paths and regular expressions (lesson 50).
Indexing
Each character has a position, starting at 0. Negative indexes count from the end:
word = "Python" print(word[0], word[1]) print(word[-1], word[-2]) print(len(word))
P y n o 6
word = "Python" print(word[10])
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(word[10])
~~~~^^^^
IndexError: string index out of rangeSlicing
text[start:stop] returns the characters from start up to but not including stop. Either can be left out, and an optional third number is the step:
s = "Hello, World" print(s[0:5]) print(s[7:]) print(s[:5]) print(s[-5:]) print(s[::2]) print(s[::-1])
Hello World Hello World Hlo ol dlroW ,olleH
[::-1] is the idiomatic way to reverse a string. Slices never raise an index error — out-of-range bounds are simply clipped. Lesson 26 covers slicing for all sequences.
Strings are immutable
name = "Jello" name[0] = "H"
Traceback (most recent call last):
File "main.py", line 2, in <module>
name[0] = "H"
~~~~^^^
TypeError: 'str' object does not support item assignmentBuild a new string instead: name = "H" + name[1:]. Every string method also returns a new string, leaving the original untouched.
Combining and repeating
first = "Grace" last = "Hopper" print(first + " " + last) print("-" * 20) print("ha" * 3) print(" ".join(["a", "b", "c"]))
Grace Hopper -------------------- hahaha a b c
When joining many pieces, "".join(list_of_strings) is much faster than repeated +.
Membership and comparison
email = "ada@example.com" print("@" in email) print("gmail" not in email) print("apple" < "banana", "Zebra" < "apple") print("Yes".lower() == "yes")
True True True True True
Comparisons use Unicode order, so uppercase letters sort before lowercase. Normalise case before comparing user input.
Looping over a string
for ch in "hey": print(ch, ord(ch)) print(chr(9731))
h 104 e 101 y 121 ☃
ord() gives a character's Unicode code point and chr() does the reverse.