
Python
Master method chaining, edge cases, case folding, and locale-aware operations.
# Chain multiple methods for data transformation
text = " HELLO world "
result = text.strip().lower().replace("hello", "hi")
print(result) # hi world
# Complex transformation pipeline
def process_name(input_text):
return (input_text
.strip()
.title()
.replace("'", "")
.replace("-", " "))
print(process_name(" o'brien-smith "))
# O Brien Smith
# Performance: Each method creates new string
# " HELLO " β "HELLO " β "hello " β "hello world " β "hi world "# case_fold() for case-insensitive comparisons
german_text = "StraΓe"
print(german_text.lower()) # straΓe
print(german_text.casefold()) # strasse (more aggressive)
# For internationalization
import locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
# Turkish I problem
text = "Istanbul"
print(text.lower()) # istanbul
print(text.casefold()) # istanbul
# Turkish has two i's: i and Δ±
# Use casefold for robust comparison
email1 = "User@Example.COM"
email2 = "user@example.com"
print(email1.casefold() == email2.casefold()) # True# Combining characters
import unicodedata
text1 = "Γ©" # Single character
text2 = "e\u0301" # e + combining acute
print(text1 == text2) # False!
print(len(text1), len(text2)) # 1, 2
# Normalize for comparison
norm1 = unicodedata.normalize("NFC", text1)
norm2 = unicodedata.normalize("NFC", text2)
print(norm1 == norm2) # True
# Useful normalization forms
text = "cafΓ©"
print(unicodedata.normalize("NFD", text)) # Decomposed
print(unicodedata.normalize("NFC", text)) # Composed| Method | Behavior | Use Case |
|---|---|---|
| `partition()` | Split into 3 parts | Parsing structured text |
| `rpartition()` | Split from right | Extract suffix |
| `expandtabs()` | Replace tabs | Format output |
| `translate()` | Character mapping | Fast bulk replacement |
| `maketrans()` | Build translation table | Encryption/obfuscation |
# partition() returns (before, separator, after)
url = "user:password@host:5432"
before, sep, after = url.partition("@")
print(f"Credentials: {before}, Host: {after}")
# Credentials: user:password, Host: host:5432
# rpartition() from the right
email = "john.doe+tag@example.com"
user, sep, domain = email.rpartition("@")
print(f"User: {user}, Domain: {domain}")
# Useful for key-value parsing
config = "database.host=localhost"
key, sep, value = config.partition("=")
if sep:
print(f"Setting {key} = {value}")# Fast character replacement without regex
text = "Hello 123 World!"
# Create translation table
table = str.maketrans("0123456789", "9876543210")
result = text.translate(table)
print(result) # Hello 987 654 321 World!
# Remove characters
punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
table = str.maketrans("", "", punctuation)
clean = "Hello! World? Yes!".translate(table)
print(clean) # Hello World Yes
# Cipher example: ROT13
def rot13(text):
from string import ascii_letters
letters = ascii_letters
shifted = ascii_letters[13:] + ascii_letters[:13]
table = str.maketrans(letters, shifted)
return text.translate(table)
print(rot13("Hello World")) # Uryyb Jbeyq# expandtabs() - replace tabs with spaces
text = "Name\tAge\tCity"
print(text) # Name Age City
print(text.expandtabs(20)) # Name Age City
# splitlines() with keepends
text = "line1\nline2\rline3\r\nline4"
lines = text.splitlines(keepends=True)
for line in lines:
print(repr(line))
# 'line1\n'
# 'line2\r'
# 'line3\r\n'
# 'line4'
# Strip specific characters
text = "...hello..."
print(text.strip(".")) # hello
print(text.lstrip(".")) # hello...
print(text.rstrip(".")) # ...helloimport timeit
# For repeated replacements, translate is faster
text = "The quick brown fox" * 1000
# Method 1: Multiple replace calls
def method_replace(t):
return t.replace("a", "@").replace("e", "3").replace("i", "1")
# Method 2: Using translate
def method_translate(t):
table = str.maketrans("aei", "@31")
return t.translate(table)
# Method 3: Using regex
import re
def method_regex(t):
return re.sub("[aei]", lambda m: {"a": "@", "e": "3", "i": "1"}[m.group()], t)
print("replace:", timeit.timeit(lambda: method_replace(text), number=100))
print("translate:", timeit.timeit(lambda: method_translate(text), number=100))
print("regex:", timeit.timeit(lambda: method_regex(text), number=100))| Concept | Remember |
|---|---|
| Chain methods | Each returns new string; enables fluent style |
| casefold() vs lower() | Use casefold() for Unicode-aware comparison |
| Normalization | Use Unicode NFC for reliable string comparison |
| partition() | Cleaner than split() for key-value parsing |
| translate() | Fastest for bulk character replacement |
Learn advanced string formatting and localization.
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward