Strings

Strings (str) are immutable sequences of characters. They support a rich set of methods for searching, transforming, and formatting text.

Creating Strings

s1 = 'single quotes'
s2 = "double quotes"
s3 = """triple quotes
for multi-line"""
s4 = r"raw string: \n is literal"

Common Operations

text = "Hello, World!"

len(text)           # 13 — length
text[0]             # 'H' — indexing
text[-1]            # '!' — negative indexing
text[0:5]           # 'Hello' — slicing
text[7:]            # 'World!'
"Hello" in text     # True — membership
text * 2            # 'Hello, World!Hello, World!'

Python Playground
Output
Click "Run" to execute your code

Case Methods

Method Description Example
upper() All uppercase "hello".upper()"HELLO"
lower() All lowercase "HELLO".lower()"hello"
title() Title case "hello world".title()"Hello World"
capitalize() First char upper "hello".capitalize()"Hello"
swapcase() Swap case "Hello".swapcase()"hELLO"
casefold() Aggressive lowercase "Straße".casefold()"strasse"

Search Methods

Method Description Example
find(sub) Index of first match, -1 if not found "hello".find("ll")2
rfind(sub) Index of last match "hello".rfind("l")3
index(sub) Like find, but raises ValueError "hello".index("ll")2
count(sub) Count occurrences "hello".count("l")2
startswith(s) Check prefix "hello".startswith("he")True
endswith(s) Check suffix "hello".endswith("lo")True

Modification Methods

Method Description Example
replace(old, new) Replace occurrences "hello".replace("l", "r")"herro"
strip() Remove leading/trailing whitespace " hi ".strip()"hi"
lstrip() Remove leading whitespace " hi ".lstrip()"hi "
rstrip() Remove trailing whitespace " hi ".rstrip()" hi"
center(w) Center in width "hi".center(10)" hi "
ljust(w) Left justify "hi".ljust(10)"hi "
rjust(w) Right justify "hi".rjust(10)" hi"
zfill(w) Zero-pad "42".zfill(5)"00042"

Split and Join

# Splitting
"a,b,c".split(",")          # ['a', 'b', 'c']
"hello world".split()        # ['hello', 'world']
"a\nb\nc".splitlines()       # ['a', 'b', 'c']

# Joining
",".join(["a", "b", "c"])    # 'a,b,c'
" ".join(["hello", "world"]) # 'hello world'

Python Playground
Output
Click "Run" to execute your code

Test Methods

Method Description
isalpha() All alphabetic?
isdigit() All digits?
isalnum() All alphanumeric?
isspace() All whitespace?
isupper() All uppercase?
islower() All lowercase?
istitle() Title case?

String Formatting

name = "Alice"
age = 30

# F-strings (recommended)
f"Name: {name}, Age: {age}"

# format() method
"Name: {}, Age: {}".format(name, age)
"Name: {n}, Age: {a}".format(n=name, a=age)

# Format specifiers
f"{3.14159:.2f}"      # '3.14'
f"{42:05d}"           # '00042'
f"{1000000:,}"        # '1,000,000'
f"{'hi':>10}"         # '        hi'
f"{'hi':<10}"         # 'hi        '
f"{'hi':^10}"         # '    hi    '