Python String Examples
A runnable cookbook of everyday Python string tasks — reverse, change case, split, join, replace, strip, search, count and format — each a short snippet you can run in the browser.
Overview
Short, copy-paste examples for the most common things you do with strings in Python. Run any of them in the online Python compiler.
Examples
Reverse a string
s = "hello"
print(s[::-1]) # olleh
Uppercase and lowercase
s = "Hello World"
print(s.upper()) # HELLO WORLD
print(s.lower()) # hello world
Split into a list
row = "name,age,city"
print(row.split(",")) # ['name', 'age', 'city']
Join a list into a string
parts = ["a", "b", "c"]
print("-".join(parts)) # a-b-c
Replace text
s = "one fish two fish"
print(s.replace("fish", "cat")) # one cat two cat
Strip surrounding whitespace
s = " hello "
print(s.strip()) # 'hello'
print(repr(s.strip())) # 'hello'
Check if it contains a substring
s = "xcodx.io/editor"
print("editor" in s) # True
print(s.startswith("xcodx")) # True
Count occurrences
s = "banana"
print(s.count("a")) # 3
Format numbers with an f-string
name = "Ada"
score = 0.9137
print(f"{name} scored {score:.1%}") # Ada scored 91.4%
Reverse the words in a sentence
sentence = "the quick brown fox"
print(" ".join(sentence.split()[::-1])) # fox brown quick the
Frequently asked questions
How do I reverse a string in Python?
Use the slice
s[::-1], which returns a new reversed string, e.g. "hello"[::-1] is "olleh".How do I split a string into a list?
Use
s.split(sep). With no argument it splits on any run of whitespace and drops empty pieces.How do I count how many times a substring appears?
Use
s.count(sub), e.g. "banana".count("a") returns 3.