Cheat sheetCore Python

Python String Cheat Sheet: Methods and Formatting

Short answer
Python strings are immutable text: use slicing to cut them, methods such as upper(), strip(), split() and replace() to transform them (each returns a new string), and f-strings to format them.

This sheet lists the string operations you reach for most, with the real output of each line. For the story behind them read Python strings and string methods.

One rule explains most surprises: a string never changes in place. s.upper() leaves s untouched, so assign the result (s = s.upper()) if you want to keep it.

Python string indexing and slicing cheat sheet

Assume `s = "Python 3.13"`. Indexes start at 0, negative indexes count from the end.
TaskCodeResult
First characters[0]'P'
Last characters[-1]'3'
Slice start to stops[2:6]'thon'
First three characterss[:3]'Pyt'
Everything from index 4s[4:]'on 3.13'
Every second characters[::2]'Pto .3'
Reverse a strings[::-1]'31.3 nohtyP'
Lengthlen(s)11
Repeats[:2] * 3'PyPyPy'
Concatenates[:2] + "-" + s[-2:]'Py-13'
Loop over characters[c for c in s[:3]]['P', 'y', 't']

Python string case and whitespace methods

Assume `s = "pYthon rocks"` and `t = " padded text \n"`. Each method returns a new string.
TaskCodeResult
Uppercases.upper()'PYTHON ROCKS'
Lowercases.lower()'python rocks'
Title cases.title()'Python Rocks'
Capitalize first letter onlys.capitalize()'Python rocks'
Swap cases.swapcase()'PyTHON ROCKS'
Strip both endst.strip()'padded text'
Strip left onlyt.lstrip()'padded text \n'
Strip right onlyt.rstrip()' padded text'
Strip chosen characters"--ok--".strip("-")'ok'
Compare ignoring case"Py".casefold() == "pY".casefold()True
Capitalize a sentence"hello world".capitalize()'Hello world'

Python string search and test methods

str.index() works like find() but raises ValueError when the text is absent, so use find() when a miss is normal.

Assume `s = "python rocks, python works"`.
TaskCodeResult
Does it contain text?"rock" in sTrue
Starts withs.startswith("py")True
Ends withs.endswith(("ks", "ed"))True
Position of first match (-1 if none)s.find("o")4
Missing text with finds.find("z")-1
Position, but raise if missings.index("o")4
Count non-overlapping matchess.count("o")4
Only digits?"2026".isdigit()True
Only letters?"abc".isalpha()True
Letters or digits?"abc123".isalnum()True
Is it lowercase?s.islower()True
Empty-string checknot ""True

Python string split, join and replace cheat sheet

TaskCodeResult
Split on whitespace"a b c".split()['a', 'b', 'c']
Split on a separator"a,b,c".split(",")['a', 'b', 'c']
Limit the number of splits"a-b-c".split("-", 1)['a', 'b-c']
Split lines"x\ny\n".splitlines()['x', 'y']
Partition at the first separator"key=value=2".partition("=")('key', '=', 'value=2')
Join with a separator", ".join(["red", "green"])'red, green'
Join numbers (convert first)"+".join(str(n) for n in [1, 2])'1+2'
Replace all"banana".replace("a", "o")'bonono'
Replace first only"banana".replace("a", "o", 1)'bonana'
Remove spaces everywhere"a b c".replace(" ", "")'abc'
Text to list of characterslist("abc")['a', 'b', 'c']
Words of a sentence"to be or not".split()['to', 'be', 'or', 'not']

Python string formatting and f-string cheat sheet

Assume `name = "Asha"`, `price = 4.5`, `qty = 7`.
TaskCodeResult
Insert a variablef"Hi {name}"'Hi Asha'
Expression inside bracesf"{price * qty}"'31.5'
Two decimal placesf"{price:.2f}"'4.50'
Thousands separatorf"{1234567:,}"'1,234,567'
Percentf"{0.256:.1%}"'25.6%'
Pad to width, right alignedf"{qty:>5}"' 7'
Pad with zerosf"{qty:03d}"'007'
Center in a width"ab".center(6, "*")'**ab**'
Show the expression and valuef"{qty=}"'qty=7'
format() method"{} costs {:.1f}".format(name, price)'Asha costs 4.5'
repr inside an f-stringf"{name!r}""'Asha'"
Binary and hexf"{10:b} {255:x}"'1010 ff'

Python character codes and conversions cheat sheet

TaskCodeResult
Character to code pointord("A")65
Code point to characterchr(97)'a'
Text to intint("12") + 113
Number to textstr(12) + "px"'12px'
Text to floatfloat("2.5")2.5
Count each character{c: "hello".count(c) for c in "helo"}{'h': 1, 'e': 1, 'l': 2, 'o': 1}
Is it a palindrome?w == w[::-1]True
Sorted letters (anagram key)sorted("listen") == sorted("silent")True
Count vowelssum(c in "aeiou" for c in "education")5
Encode to bytes"é".encode("utf-8")b'\xc3\xa9'
Decode bytesb"caf\xc3\xa9".decode("utf-8")'café'
Count lineslen("a\nb".splitlines())2

Which Python string method should I use?

Pick by intent. To check, use in, startswith() or isdigit(). To clean input, use strip() and lower(). To break text apart use split(), and to build text from pieces use join() or an f-string. Python has no string append: because strings are immutable, build a list and join it when you add many pieces.

Examples you can run

Press Run, then edit the code and run it again.

Clean and format user input

Strip spaces, normalise case and format a message.

Clean and format user input
raw = "  asha PATEL "
name = raw.strip().title()
print(name)
print(f"Hello, {name}! ({len(name)} letters)")
Expected outputAsha Patel
Hello, Asha Patel! (10 letters)

Split, transform and join

A very common pattern: split into words, change each, join back.

Split, transform and join
sentence = "python is fun"
print(" ".join(w.capitalize() for w in sentence.split()))
print(sentence[::-1])
Expected outputPython Is Fun
nuf si nohtyp

Python String Cheat Sheet: Methods and Formatting: questions people ask

How do I change a character in a Python string?

You cannot modify a string in place because strings are immutable. Build a new string, for example s[:2] + "X" + s[3:] or s.replace("a", "X").

What is the difference between find() and index()?

find() returns -1 when the text is missing, while index() raises ValueError. Use find() when absence is an expected outcome.

How do I check if a string contains a substring?

Use the in operator, for example "rock" in s. It returns True or False and is case-sensitive.

Keep learning

Step-by-step lessons:
Python StringsPython String MethodsPython f-Strings

Related:
Python Cheat Sheet (Python 3.13 Quick Reference)Python Regex Cheat Sheet (re Module Quick Reference)Python String split() MethodHow to Check if a String Contains a Substring in Python

More in core python:
Python Cheat Sheet (Python 3.13 Quick Reference)Python List Cheat Sheet: Methods and ExamplesPython Dictionary Cheat Sheet: Methods and ExamplesPython Control Flow Cheat Sheet: if, for, while, matchPython Functions Cheat Sheet: def, args, lambda, scopePython OOP Cheat Sheet: Classes, Inheritance, Dunder MethodsPython Regex Cheat Sheet (re Module Quick Reference)Python File Handling Cheat Sheet: open, read, write, CSV, JSON See all →