Skip to main content
Albero Academy

Python Strings

Complete guide to Python strings — creation, indexing, slicing, methods, formatting, regex basics and real-world use cases.

Chapter 5Python20 min readBeginner friendly
  • #Python
  • #Strings
  • #Text

Strings show up in every program — file names, user input, API responses. Python's str is unicode-aware by default, immutable, and rich in built-in methods.

Creating strings

Python
# Three quote styles
single = 'hello'
double = "hello"
multi = """spans
multiple
lines"""
# Raw strings — backslashes are literal (great for paths and regex)
path = r"C:\Users\Aanya\Desktop"
pattern = r"\d{3}-\d{4}"
# Concatenation
greet = "Hello, " + "Aanya"
greet = "Hi " * 3 # 'Hi Hi Hi '
# Length
print(len("Albero")) # 6

Indexing & slicing

Python
s = "Albero Academy"
print(s[0]) # 'A'
print(s[-1]) # 'y'
print(s[:6]) # 'Albero'
print(s[7:]) # 'Academy'
print(s[::-1]) # 'ymedacA orebla' — reversed

Essential methods

MethodReturns
s.lower() / s.upper()all lowercase / uppercase
s.strip()remove leading & trailing whitespace
s.lstrip() / s.rstrip()remove from left / right only
s.startswith(x) / s.endswith(x)bool
s.find(x)index of first x, or -1 if not found
s.replace(a, b)new string with a replaced by b
s.split(sep)list of substrings
sep.join(iterable)concatenate with sep between
s.isdigit() / s.isalpha()bool
s.title() / s.capitalize()title-cased / first-letter-cap
Python
s = " Albero Academy "
print(s.strip()) # 'Albero Academy'
print(s.lower()) # ' albero academy '
print(s.replace("Albero", "Albero 🌱"))
print(s.startswith(" Alb")) # True
print("123".isdigit()) # True
print("abc".isalpha()) # True

f-strings & formatting

F-strings are the standard way to format. They support inline math, format specifiers, and any Python expression.

Python
name = "Aanya"
salary = 1240000
print(f"Hi {name}, your CTC is ₹{salary:,}.")
# Hi Aanya, your CTC is ₹12,40,000.
# Format specifiers
pi = 3.14159
print(f"{pi:.2f}") # 3.14 — 2 decimals
print(f"{pi:10.2f}") # ' 3.14' — width 10
print(f"{42:>10}") # right-align in 10
print(f"{42:<10}") # left-align
print(f"{42:^10}") # centred
print(f"{0.875:.0%}") # 88% — percentage

split · join · replace

Python
# split breaks a string into a list
csv = "Aanya,28,Noida,Analyst"
fields = csv.split(",")
# ['Aanya', '28', 'Noida', 'Analyst']
# join is the inverse
parts = ["data", "warehousing", "101"]
slug = "-".join(parts)
# 'data-warehousing-101'
# replace returns a new string
text = "I love coffee. Coffee is life."
print(text.replace("coffee", "tea"))
# 'I love tea. Coffee is life.' — case-sensitive!

Regex basics

Python
import re
text = "Contact: aanya@albero.com, phone: 9810012345"
# Find all email addresses
emails = re.findall(r"[\w.+-]+@[\w.-]+\.[a-z]{2,}", text)
# ['aanya@albero.com']
# Find all 10-digit phone numbers
phones = re.findall(r"\b\d{10}\b", text)
# ['9810012345']
# Substitution
masked = re.sub(r"\b\d{10}\b", "XXXX-XXXXXX", text)

Encoding & bytes

Python
s = "Albero 🌱"
b = s.encode("utf-8")
print(b)
# b'Albero \xf0\x9f\x8c\xb1'
print(b.decode("utf-8"))
# Albero 🌱
# When reading files
with open("data.csv", "rb") as f:
raw_bytes = f.read()
text = raw_bytes.decode("utf-8")

Key takeaways

  1. 01Strings are immutable; every operation returns a new string.
  2. 02Slicing works exactly like lists; [::-1] reverses.
  3. 03f-strings are the standard for formatting — they support format specs and any expression.
  4. 04split / join / replace handle 80% of text wrangling without regex.
  5. 05Reach for re for anything pattern-based — emails, phone numbers, dates.
  6. 06Python 3 strings are unicode; encode/decode at I/O boundaries with utf-8.