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

PY create.py
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)
Output
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

PY escapes.py
print("Tab:\tafter tab")
print("New\nline")
print("Backslash: \\")
print("Unicode: caf\u00e9 \N{GREEK SMALL LETTER PI}")
print(r"C:\new\table")
Output
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:

PY index.py
word = "Python"

print(word[0], word[1])
print(word[-1], word[-2])
print(len(word))
Output
P y
n o
6
PY index_error.py
word = "Python"
print(word[10])
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(word[10])
          ~~~~^^^^
IndexError: string index out of range

Slicing

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:

PY slice.py
s = "Hello, World"

print(s[0:5])
print(s[7:])
print(s[:5])
print(s[-5:])
print(s[::2])
print(s[::-1])
Output
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

PY immutable.py
name = "Jello"
name[0] = "H"
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    name[0] = "H"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

Build a new string instead: name = "H" + name[1:]. Every string method also returns a new string, leaving the original untouched.

Combining and repeating

PY combine.py
first = "Grace"
last = "Hopper"

print(first + " " + last)
print("-" * 20)
print("ha" * 3)
print(" ".join(["a", "b", "c"]))
Output
Grace Hopper
--------------------
hahaha
a b c

When joining many pieces, "".join(list_of_strings) is much faster than repeated +.

Membership and comparison

PY membership.py
email = "ada@example.com"

print("@" in email)
print("gmail" not in email)
print("apple" < "banana", "Zebra" < "apple")
print("Yes".lower() == "yes")
Output
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

PY loop.py
for ch in "hey":
    print(ch, ord(ch))

print(chr(9731))
Output
h 104
e 101
y 121
☃

ord() gives a character's Unicode code point and chr() does the reverse.

Try it yourself

Try it yourself
Console output