Python String Cheat Sheet: Methods and Formatting
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
| Task | Code | Result |
|---|---|---|
| First character | s[0] | 'P' |
| Last character | s[-1] | '3' |
| Slice start to stop | s[2:6] | 'thon' |
| First three characters | s[:3] | 'Pyt' |
| Everything from index 4 | s[4:] | 'on 3.13' |
| Every second character | s[::2] | 'Pto .3' |
| Reverse a string | s[::-1] | '31.3 nohtyP' |
| Length | len(s) | 11 |
| Repeat | s[:2] * 3 | 'PyPyPy' |
| Concatenate | s[:2] + "-" + s[-2:] | 'Py-13' |
| Loop over characters | [c for c in s[:3]] | ['P', 'y', 't'] |
Python string case and whitespace methods
| Task | Code | Result |
|---|---|---|
| Uppercase | s.upper() | 'PYTHON ROCKS' |
| Lowercase | s.lower() | 'python rocks' |
| Title case | s.title() | 'Python Rocks' |
| Capitalize first letter only | s.capitalize() | 'Python rocks' |
| Swap case | s.swapcase() | 'PyTHON ROCKS' |
| Strip both ends | t.strip() | 'padded text' |
| Strip left only | t.lstrip() | 'padded text \n' |
| Strip right only | t.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.
| Task | Code | Result |
|---|---|---|
| Does it contain text? | "rock" in s | True |
| Starts with | s.startswith("py") | True |
| Ends with | s.endswith(("ks", "ed")) | True |
| Position of first match (-1 if none) | s.find("o") | 4 |
| Missing text with find | s.find("z") | -1 |
| Position, but raise if missing | s.index("o") | 4 |
| Count non-overlapping matches | s.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 check | not "" | True |
Python string split, join and replace cheat sheet
| Task | Code | Result |
|---|---|---|
| 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 characters | list("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
| Task | Code | Result |
|---|---|---|
| Insert a variable | f"Hi {name}" | 'Hi Asha' |
| Expression inside braces | f"{price * qty}" | '31.5' |
| Two decimal places | f"{price:.2f}" | '4.50' |
| Thousands separator | f"{1234567:,}" | '1,234,567' |
| Percent | f"{0.256:.1%}" | '25.6%' |
| Pad to width, right aligned | f"{qty:>5}" | ' 7' |
| Pad with zeros | f"{qty:03d}" | '007' |
| Center in a width | "ab".center(6, "*") | '**ab**' |
| Show the expression and value | f"{qty=}" | 'qty=7' |
| format() method | "{} costs {:.1f}".format(name, price) | 'Asha costs 4.5' |
| repr inside an f-string | f"{name!r}" | "'Asha'" |
| Binary and hex | f"{10:b} {255:x}" | '1010 ff' |
Python character codes and conversions cheat sheet
| Task | Code | Result |
|---|---|---|
| Character to code point | ord("A") | 65 |
| Code point to character | chr(97) | 'a' |
| Text to int | int("12") + 1 | 13 |
| Number to text | str(12) + "px" | '12px' |
| Text to float | float("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 vowels | sum(c in "aeiou" for c in "education") | 5 |
| Encode to bytes | "é".encode("utf-8") | b'\xc3\xa9' |
| Decode bytes | b"caf\xc3\xa9".decode("utf-8") | 'café' |
| Count lines | len("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.
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.
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 →