Strings - Classroom Notes
What is a String?
A string is a sequence of characters, like a word or a sentence."hello world"
How to Create a String
You can use single or double quotes:
s1 = 'apple'
s2 = "banana"
Tip: Quotes must match!
Strings are Immutable
You can't change a string after it's created!
s = "cat"
s[0] = "b" # ❌ Error!
s[0] = "b" # ❌ Error!
To "change" a string, make a new one.
Indexing & Slicing
s = "python"s[0] # 'p' s[2:5] # 'tho'
Indexes start at 0. Slicing is
[start:end]
(end not included).Concatenation
greet = "Hi, " + "Alice!"
# 'Hi, Alice!'
Common String Methods
s = "hello"s.upper() # 'HELLO' s.replace("l", "r") # 'herro' s.split("e") # ['h', 'llo']
Try:
lower()
, strip()
, find()
, join()
, ...Fun Fact
Strings can be empty: ""
An empty string has length 0!
String Literals vs Variables
'hello' is a literal
greet = 'hello' is a variable
A literal is a value; a variable stores it for reuse.
Escape Characters
s = 'It\'s sunny!'
newline = "Line1\nLine2"
Use
\n
for new line, \t
for tab, \\
for backslash, \'
or \"
for quotes.Multi-line Strings
msg = """Hello\nWorld!"""
Triple quotes let you write strings over multiple lines.
String Formatting
name = "Sam""Hello, %s!" % name # 'Hello, Sam!' "Hello, {}!".format(name) # 'Hello, Sam!' f"Hello, {name}!" # 'Hello, Sam!'
f-strings (since Python 3.6) are the most modern and readable!
Membership & Iteration
'a' in "cat" # True
for ch in "dog": print(ch)
You can check if a substring exists, or loop through each character.
Length of a String
len("banana") # 6
Use
len()
to count characters (including spaces and symbols).Common Pitfalls
s = "123"n = s + 1 # ❌ Error!
You can't add a string and a number directly. Use
s = "hello"int(s)
or str(n)
to convert.s[0] = 'y' # ❌ Error!
Strings are immutable—use
s = 'y' + s[1:]
to "change" the first letter.Real-World Analogy
Each bead is a character. You can count, pick, or slice beads, but can't change one in place!