The modern Python strings cheat sheet

Updated: May 24, 2023 By: Wolf Post a comment

This page provides a comprehensive, example-style cheat sheet about strings in modern Python (Python 3.10 and newer versions). I also use it quite often for quick lookups when building projects. You can bookmark it as a handy reference for later use.

Creating strings

name = "Ranni the Witch"
message = 'Welcome to Sling Academy'

String length

text = "Hello"
length = len(text)

Accessing characters

text = "Hello"
first_char = text[0] # H
last_char = text[-1] # o

String slicing

text = "Hello, World!"
substring = text[7:12]  # Output: "World"

String concatenation

greeting = "Hello"
name = "Wolf"
message = greeting + ", " + name + "!"  # Output: "Hello, Wolf!"

String case conversion (lower case & upper case)

text = "Hello, World!"
upper_case = text.upper()  # Output: "HELLO, WORLD!"
lower_case = text.lower()  # Output: "hello, world!"

String Formatting with f-strings

name = "Wolf"
age = 99
message = f"My name is {name} and I am {age} years old."  # Output: "My name is Wolf and I am 99 years old."

String searching

text = "Hello, World!"
contains_hello = "Hello" in text  # Output: True
index_hello = text.index("Hello")  # Output: 0

String splitting

text = "Welcome to slingacademy.com!"

# split the text by space
words = text.split(" ") 
# Output: ['Welcome', 'to', 'slingacademy.com!']

String stripping

text = "   Hello, World!   "
stripped_text = text.strip()  # Output: "Hello, World!"

String reversed

text = "Hello"
reversed_text = text[::-1]  # Output: "olleH"

Remove prefixes and remove suffixes

text = "Hello, World!"
removed_prefix = text.removeprefix("Hello, ")  # Output: "World!"
removed_suffix = text.removesuffix("!")  # Output: "Hello, World"

String replacing

text = "Hello, World!"
new_text = text.replace("Hello", "Hi")  # Output: "Hi, World!"

String alignment

text = "Hello"
left_aligned = text.ljust(10)  # Output: "Hello     "
right_aligned = text.rjust(10)  # Output: "     Hello"
centered = text.center(10)  # Output: "  Hello   "

String partitioning

text = "Hello, World!"
partitioned = text.partition(",")  # Output: ("Hello", ",", " World!")
rpartitioned = text.rpartition(" ")  # Output: ("Hello,"," ","World!")