Strings
f-strings, methods, slicing, and text processing
Skills taught: python.strings, python.f-strings, python.string-methods
String basics and f-strings
# Single, double, or triple quotes
name = 'Prashant'
quote = "It's easy"
essay = '''This is a
multiline string'''
# f-strings (Python 3.6+) — most modern way
age = 28
print(f'Name: {name}, Age: {age}') # Name: Prashant, Age: 28
print(f'{name!r}') # 'Prashant' (repr)
print(f'{3.14159:.2f}') # 3.14 (2 decimal places)
print(f'{1000000:,}') # 1,000,000 (thousands separator)
print(f'{"hello":^20}') # centered in 20 chars
print(f'{42:08d}') # 00000042 (zero-padded)
# Raw strings — no escape processing
path = r'C:\Users\Prashant\Documents'
print(path) # C:\Users\Prashant\Documents
Essential string methods
text = ' Hello, World! '
# Case
print(text.upper()) # ' HELLO, WORLD! '
print(text.lower()) # ' hello, world! '
print(text.title()) # ' Hello, World! '
# Whitespace
print(text.strip()) # 'Hello, World!' (both ends)
print(text.lstrip()) # 'Hello, World! ' (left only)
print(text.rstrip()) # ' Hello, World!' (right only)
# Search
print('World' in text) # True
print(text.find('World')) # 9 (index), -1 if not found
print(text.startswith(' ')) # True
print(text.endswith('! ')) # True
print(text.count('l')) # 3
# Modify (returns NEW string)
print(text.replace('World', 'Python'))
print(text.strip().split(', ')) # ['Hello', 'World!']
# Join — opposite of split
words = ['Hello', 'World']
print(', '.join(words)) # Hello, World
print('-'.join(['a','b','c'])) # a-b-c
# Check content
print('123'.isdigit()) # True
print('abc'.isalpha()) # True
print('abc123'.isalnum()) # True
Frequently Asked Questions
How do I efficiently build a string in a loop?
Don't use += in a loop (O(n²) — creates a new string each time). Instead: collect parts in a list, then join: parts = []; for x in items: parts.append(str(x)); result = ', '.join(parts). This is O(n).
What is the difference between find() and index()?
Both search for a substring. find() returns -1 if not found. index() raises ValueError if not found. Use find() when absence is expected; use index() when absence is an error.