Site

Strings — Python str Operations

Tutorial S1  •  Python / Learn

S1.0 What This Teaches

This tutorial covers the Python str type and its operations:

S1.1 Strings are Immutable

Python strings are immutable Unicode sequences. Every method that appears to modify a string returns a new string; the original is unchanged:
s = "hello"
upper = s.upper()   # new string "HELLO"
print(s)            # still "hello"
print(upper)        # "HELLO"

# == compares content
a = "hello"
b = "hel" + "lo"
print(a == b)   # True
print(a is b)   # True in CPython (string interning), but do not rely on this

S1.2 Slicing and Indexing

s = "Hello, World!"

print(s[0])        # 'H'
print(s[-1])       # '!'
print(s[7:12])     # 'World'
print(s[:5])       # 'Hello'
print(s[7:])       # 'World!'
print(s[::2])      # 'Hlo ol!'  (every other character)
print(s[::-1])     # '!dlroW ,olleH'  (reversed)
Slice syntax: s[start:stop:step]. Negative indices count from the end. Strings can be iterated with for ch in s.

S1.3 Common str Methods

s = "  Hello, World!  "
print(s.strip())          # "Hello, World!"
print(s.lstrip())         # "Hello, World!  "
print(len(s))             # 18

s = "Hello, World!"
print(s.upper())          # "HELLO, WORLD!"
print(s.lower())          # "hello, world!"
print(s.replace(",", ";"))         # "Hello; World!"
print(s.startswith("Hello"))       # True
print(s.endswith("!"))             # True
print(s.find("World"))             # 7 (or -1 if not found)
print(s.count("l"))                # 3

parts = s.split(", ")     # ['Hello', 'World!']
joined = " | ".join(parts)         # 'Hello | World!'
print(joined)

S1.4 String Formatting

name = "Alice"
score = 98.7

# f-string (Python 3.6+) - preferred
print(f"Name: {name}, score: {score:.1f}")

# .format() - older, still useful for templates
template = "Name: {}, score: {:.1f}"
print(template.format(name, score))

# % formatting - oldest style, avoid in new code
print("Name: %s, score: %.1f" % (name, score))

# Format specifiers
pi = 3.14159
print(f"{pi:.2f}")    # 3.14
print(f"{1000:,}")    # 1,000
print(f"{'left':<10}|")   # 'left      |'
print(f"{'right':>10}|")  # '     right|'

S1.5 Multiline and Raw Strings

# Triple-quoted multiline string (leading/trailing newlines included)
poem = """Roses are red,
Violets are blue,
Python is great,
And so are you."""

# Raw string - backslashes are literal
path = r"C:\Users\Alice\Documents"
pattern = r"\d{3}-\d{4}"   # useful for regex

# Byte string
b = b"hello"   # bytes, not str; use for binary data
print(type(b))   # <class 'bytes'>
text = b.decode("utf-8")   # bytes -> str
raw = text.encode("utf-8") # str -> bytes

S1.6 Example - All Together

# Strings - word frequency counter using str methods.

from collections import Counter

text = "the quick brown fox jumps over the lazy dog the fox"
words = text.lower().split()
freq = Counter(words)

print("Top words:")
for word, count in freq.most_common(5):
    print(f"  {word:<10} {count}")
Expected output:
Top words:
  the        3
  fox        2
  quick      1
  brown      1
  jumps      1

S1.7 Exercise

Exercise
  • Write a function title_case(s: str) -> str that capitalizes the first letter of each word. Do not use the built-in .title() method - implement it with split() and join().
  • Write a function is_palindrome(s: str) -> bool that ignores spaces and case. Use slicing to reverse and compare.
  • Use an f-string to format a table of 5 student names and grades, left-aligning names and right-aligning numeric scores in fixed-width columns.

S1.8 Common Mistakes

Using + in a loop for concatenation

result = ""
for s in big_list:
    result += s   # O(n²) - creates a new string each iteration

result = "".join(big_list)   # O(n) - idiomatic and fast

Confusing find() and index()

s = "hello"
print(s.find("z"))    # -1 (not found - no exception)
print(s.index("z"))   # ValueError: substring not found
Use find() when the substring might not exist. Use index() only when you expect it to be there.

Mixing str and bytes

text = "hello"
raw = b"hello"
print(text + raw)   # TypeError: can only concatenate str (not "bytes") to str
Decode bytes to str or encode str to bytes before mixing them.

S1.9 Key Terms

TermMeaning
strImmutable Unicode text sequence; the default string type in Python 3
slices[start:stop:step] - produces a substring without copying in many cases
f-stringf"..." - embeds Python expressions directly in a string literal
raw stringr"..." - backslashes are literal; no escape processing
bytesImmutable sequence of byte values; used for binary data and network I/O
encode / decodestr.encode(enc) → bytes; bytes.decode(enc) → str
join()Efficient way to concatenate many strings: sep.join(iterable)
find() / index()Return position of substring; find returns -1, index raises on miss