Python Strings
What is a String?
A string is a sequence of characters enclosed in single, double, or triple quotes. Strings are immutable — once created, they cannot be changed in place.
Creating Strings
s1 = 'single quotes'
s2 = "double quotes"
s3 = '''triple single — spans
multiple lines'''
s4 = """triple double — also
multi-line"""
# Escape characters
tab = "Hello\tWorld" # tab
newline = "Line1\nLine2" # newline
quote = "She said \"hi\""
backslash = "C:\\Users\\Alice"
# Raw string — backslashes are literal
path = r"C:\Users\Alice\Documents"
regex = r"\d+\.\d+"
print(len("Python")) # 6
print(type("hello")) # <class 'str'>
Indexing and Slicing
s = "Python"
# P y t h o n
# 0 1 2 3 4 5 (positive index)
# -6-5-4-3-2-1 (negative index)
print(s[0]) # P
print(s[-1]) # n
print(s[2]) # t
# Slicing: s[start:stop:step]
print(s[1:4]) # yth
print(s[:3]) # Pyt
print(s[3:]) # hon
print(s[::2]) # Pto (every 2nd char)
print(s[::-1]) # nohtyP (reversed)
# Strings are immutable
# s[0] = "J" # TypeError!
# Create a new string instead:
new_s = "J" + s[1:]
print(new_s) # Jython
String Formatting
name = "Alice"
age = 25
pi = 3.14159
# f-strings (Python 3.6+) — recommended
print(f"Hello, {name}! You are {age} years old.")
print(f"Pi = {pi:.2f}") # 2 decimal places
print(f"{age:05d}") # 00025 (zero-padded)
print(f"{'left':<10}|") # left-aligned
print(f"{'right':>10}|") # right-aligned
print(f"{'center':^10}|") # centered
print(f"{1_000_000:,}") # 1,000,000 (thousands separator)
# format() method
print("Hello, {}! Age: {}".format(name, age))
print("Hello, {name}!".format(name="Bob"))
# % formatting (old style)
print("Hello, %s! Age: %d" % (name, age))
print("Pi = %.2f" % pi)
# Multiline f-string
report = (
f"Name: {name}\n"
f"Age: {age}\n"
f"Pi: {pi:.4f}"
)
print(report)
String Methods
| Method | Description | Example |
|---|---|---|
upper() | Uppercase | "hi".upper() → "HI" |
lower() | Lowercase | "HI".lower() → "hi" |
title() | Title case | "hello world".title() → "Hello World" |
strip() | Remove leading/trailing whitespace | " hi ".strip() → "hi" |
lstrip() / rstrip() | Strip left or right only | |
replace(old, new) | Replace substring | "abc".replace("b","x") → "axc" |
split(sep) | Split into list | "a,b,c".split(",") → ['a','b','c'] |
join(iterable) | Join list into string | ",".join(["a","b"]) → "a,b" |
find(sub) | Index of first occurrence (-1 if not found) | "hello".find("l") → 2 |
index(sub) | Like find but raises ValueError | |
count(sub) | Count occurrences | "hello".count("l") → 2 |
startswith(s) | Check prefix | "hello".startswith("he") → True |
endswith(s) | Check suffix | "hello".endswith("lo") → True |
isdigit() | All digits? | "123".isdigit() → True |
isalpha() | All letters? | "abc".isalpha() → True |
isalnum() | Letters or digits? | |
zfill(n) | Zero-pad to width n | "42".zfill(5) → "00042" |
center(n) | Center in width n | "hi".center(10) |
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.replace("World", "Python")) # " Hello, Python! "
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
print(" | ".join(fruits)) # apple | banana | cherry
sentence = "the quick brown fox"
print(sentence.title()) # The Quick Brown Fox
print(sentence.count("the")) # 1
print(sentence.find("quick")) # 4
print(sentence.startswith("the")) # True
# Method chaining
clean = " HELLO WORLD ".strip().lower().replace(" ", "_")
print(clean) # hello_world
String Operations
# Concatenation
first = "Hello"
last = "World"
full = first + ", " + last + "!"
print(full) # Hello, World!
# Repetition
print("ha" * 3) # hahaha
print("-" * 30) # separator line
# Membership
print("ell" in "Hello") # True
print("xyz" not in "Hello") # True
# Iteration
for char in "Python":
print(char, end=" ") # P y t h o n
# Convert to list of chars
chars = list("Python")
print(chars) # ['P', 'y', 't', 'h', 'o', 'n']
# Multiline string as template
template = """
Dear {name},
Your order #{order_id} has been shipped.
Expected delivery: {date}
Thanks,
The Team
"""
print(template.format(name="Alice", order_id=12345, date="June 20"))