Strings
Learn how to work with text in Python — string methods, formatting, and modern f-strings.
Strings
A string is a sequence of characters used to represent text. Anything inside quotes is a string — letters, numbers, symbols, spaces, all of it.
name = "Ali"
message = 'Hello, world!'
mixed = "I have 3 cats and 2 dogs."You already saw strings in the basics section. This file goes deep — methods, formatting, searching, cleaning, and modern f-strings.
Creating strings
# single or double quotes — both work the same
name = "Ali"
city = 'Lahore'
# triple quotes — for multiline text
bio = """
My name is Ali.
I am from Lahore.
I love Python.
"""
# escape characters
path = "C:\\Users\\Ali\\Documents"
tab = "name\tage\tcity"
newline = "line one\nline two"Common escape characters:
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
Raw strings — ignore escape characters completely:
path = r"C:\Users\Ali\Documents"
print(path) # C:\Users\Ali\Documents — backslashes stay as-isAccessing characters
Strings are sequences — you can access characters by index, just like lists:
name = "Python"
# 012345
print(name[0]) # P
print(name[-1]) # n — last character
print(name[1:4]) # yth — slicing
print(name[::-1]) # nohtyP — reversedStrings are immutable — you cannot change a character directly:
name = "Python"
name[0] = "J" # TypeError — strings cannot be modified in placeTo "change" a string, you create a new one.
String methods
Python gives you a large set of built-in methods to work with strings. None of them modify the original — they always return a new string.
Case methods
text = "hello world"
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.capitalize()) # Hello world — first letter uppercase only
print(text.title()) # Hello World — first letter of each word
print(text.swapcase()) # HELLO WORLD → hello world and vice versaReal use — case-insensitive comparison:
user_input = "PYTHON"
if user_input.lower() == "python":
print("Correct!")Stripping whitespace
text = " hello world "
print(text.strip()) # "hello world" — removes from both sides
print(text.lstrip()) # "hello world " — removes from left only
print(text.rstrip()) # " hello world" — removes from right onlyYou can also strip specific characters:
text = "###hello###"
print(text.strip("#")) # helloVery commonly used when cleaning user input or reading files.
Finding and checking
text = "Python is great and Python is fun"
print(text.find("Python")) # 0 — index of first match
print(text.find("Java")) # -1 — not found, no error
print(text.rfind("Python")) # 18 — index of last match
print(text.index("Python")) # 0 — like find but raises ValueError if not found
print(text.count("Python")) # 2 — how many times it appearsChecking content:
print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
print("hello".startswith("lo")) # FalseChecking what the string contains:
print("Ali123".isalnum()) # True — only letters and numbers
print("Ali".isalpha()) # True — only letters
print("123".isdigit()) # True — only digits
print(" ".isspace()) # True — only whitespace
print("Hello World".istitle()) # True — title caseReplacing
text = "I love Java. Java is great."
print(text.replace("Java", "Python"))
# I love Python. Python is great.
# replace only the first occurrence
print(text.replace("Java", "Python", 1))
# I love Python. Java is great.Removing prefixes and suffixes (Python 3.9+)
filename = "report_2024.pdf"
print(filename.removesuffix(".pdf")) # report_2024
print(filename.removeprefix("report_")) # 2024.pdfMuch cleaner than the old way of slicing strings manually.
url = "https://example.com"
print(url.removeprefix("https://")) # example.comSplitting and joining
split() — break a string into a list:
sentence = "Python is easy to learn"
words = sentence.split() # splits on whitespace by default
print(words) # ['Python', 'is', 'easy', 'to', 'learn']
csv = "ali,sara,omar,fatima"
names = csv.split(",")
print(names) # ['ali', 'sara', 'omar', 'fatima']Split with a limit:
text = "one:two:three:four"
print(text.split(":", 2)) # ['one', 'two', 'three:four']join() — combine a list into a string:
words = ["Python", "is", "easy", "to", "learn"]
sentence = " ".join(words)
print(sentence) # Python is easy to learn
csv = ",".join(["ali", "sara", "omar"])
print(csv) # ali,sara,omar
path = "/".join(["home", "ali", "documents"])
print(path) # home/ali/documentsjoin() is called on the separator, not the list. " ".join(words) — the space is the separator, words is the list. This trips up beginners at first but becomes natural quickly.
Padding and alignment
text = "Ali"
print(text.ljust(10)) # "Ali " — left aligned, padded to 10
print(text.rjust(10)) # " Ali" — right aligned
print(text.center(10)) # " Ali " — centered
print(text.center(10, "-")) # "---Ali----" — centered with fill character
print("42".zfill(5)) # "00042" — pad with zeros on the leftin — check if substring exists
text = "Python is amazing"
print("Python" in text) # True
print("Java" in text) # False
print("python" in text) # False — case sensitive
print("python" in text.lower()) # Truef-strings — modern string formatting
f-strings are the cleanest way to build strings with variables. Put f before the quote and wrap expressions in {}.
name = "Ali"
age = 22
print(f"My name is {name} and I am {age} years old.")
# My name is Ali and I am 22 years old.You can put any expression inside {}:
a = 10
b = 3
print(f"{a} + {b} = {a + b}")
print(f"{a} / {b} = {a / b:.2f}")
print(f"{'hello'.upper()}")
print(f"{2 ** 10}")Number formatting in f-strings
price = 1234567.891
print(f"{price:.2f}") # 1234567.89 — 2 decimal places
print(f"{price:,.2f}") # 1,234,567.89 — thousands separator
print(f"{price:e}") # 1.234568e+06 — scientific notation
print(f"{0.1 + 0.2:.1f}") # 0.3 — clean up float imprecision
score = 0.873
print(f"{score:.1%}") # 87.3% — as percentage
number = 255
print(f"{number:b}") # 11111111 — binary
print(f"{number:x}") # ff — hexadecimal
print(f"{number:o}") # 377 — octalAlignment in f-strings
items = [("Apple", 1.50), ("Banana", 0.75), ("Mango", 2.00)]
print(f"{'Item':<10} {'Price':>8}")
print("-" * 20)
for name, price in items:
print(f"{name:<10} {price:>8.2f}")Output:
Item Price
--------------------
Apple 1.50
Banana 0.75
Mango 2.00< means left-align, > means right-align, the number is the width.
Python 3.12 f-string improvements
Python 3.12 made f-strings much more flexible. You can now use the same quote type inside {} — no more escaping:
# Before Python 3.12 — had to use different quotes inside
student = {"name": "Ali"}
print(f"Name: {student['name']}") # had to use single quotes inside
# Python 3.12+ — same quotes work fine
print(f"Name: {student["name"]}") # works perfectly nowYou can also use backslashes inside f-string expressions in Python 3.12+:
names = ["Ali", "Sara", "Omar"]
# Python 3.12+
print(f"Names: {'\n'.join(names)}")And multi-line f-strings with complex expressions are now properly supported:
scores = [88, 92, 79, 95]
result = f"""
Students: {len(scores)}
Average: {sum(scores) / len(scores):.1f}
Highest: {max(scores)}
Lowest: {min(scores)}
"""
print(result)= specifier — debugging shortcut
Very useful when debugging — prints the variable name and its value:
name = "Ali"
age = 22
score = 88.5
print(f"{name=}") # name='Ali'
print(f"{age=}") # age=22
print(f"{score=}") # score=88.5
print(f"{2 + 2=}") # 2 + 2=4String repetition and concatenation
# concatenation
greeting = "Hello" + ", " + "world!"
print(greeting) # Hello, world!
# repetition
line = "-" * 30
print(line) # ------------------------------
border = "=" * 20
title = "REPORT"
print(border)
print(title.center(20))
print(border)Multiline strings
message = """
Dear Ali,
Your order has been confirmed.
Total: $49.99
Thank you for shopping with us.
"""
print(message)A real example
A simple receipt generator:
def generate_receipt(customer, items):
width = 35
print("=" * width)
print(f"{'RECEIPT':^{width}}")
print("=" * width)
print(f"Customer: {customer}")
print("-" * width)
print(f"{'Item':<20} {'Price':>10}")
print("-" * width)
total = 0
for item, price in items:
print(f"{item:<20} {price:>10.2f}")
total += price
print("-" * width)
print(f"{'TOTAL':<20} {total:>10.2f}")
print("=" * width)
items = [
("Python Book", 29.99),
("USB Cable", 9.99),
("Mouse Pad", 7.50),
]
generate_receipt("Ali Ahmed", items)Output:
===================================
RECEIPT
===================================
Customer: Ali Ahmed
-----------------------------------
Item Price
-----------------------------------
Python Book 29.99
USB Cable 9.99
Mouse Pad 7.50
-----------------------------------
TOTAL 47.48
===================================Summary
| Method | What it does |
|---|---|
upper() / lower() | Change case |
strip() / lstrip() / rstrip() | Remove whitespace |
find(x) / rfind(x) | Find index of substring |
count(x) | Count occurrences |
replace(old, new) | Replace substring |
removeprefix(x) | Remove prefix (3.9+) |
removesuffix(x) | Remove suffix (3.9+) |
split(sep) | Split into list |
join(list) | Join list into string |
startswith(x) / endswith(x) | Check start or end |
isdigit() / isalpha() / isalnum() | Check content type |
center() / ljust() / rjust() | Align text |
zfill(n) | Pad with zeros |
f"{var=}" | Debug print with name |