Python Strings
Text is everywhere — Python's str type handles it all.
Creating strings
Python
name = "Raman" # double quotes
city = 'Bangalore' # single quotes — identical
bio = '''Line one
Line two
Line three''' # triple quotes for multiline
f-strings (Python 3.6+) — the modern way
Python
name = "Raman"
age = 28
pi = 3.14159
print(f"Hello, {name}! You are {age} years old.")
print(f"Pi to 2 decimal places: {pi:.2f}") # 3.14
print(f"Uppercase: {name.upper()}") # RAMAN
print(f"{age * 2 = }") # age * 2 = 56 (Python 3.8+)
Slicing
Python — s[start:stop:step]
s = "Hello, World!"
s[0] # 'H' — first character
s[-1] # '!' — last character
s[0:5] # 'Hello'
s[7:] # 'World!'
s[:5] # 'Hello'
s[::-1] # '!dlroW ,olleH' — reversed
Most useful string methods
Python
s = " Hello, World! "
s.strip() # "Hello, World!" — remove whitespace
s.lower() # " hello, world! "
s.upper() # " HELLO, WORLD! "
s.replace("World", "Python") # " Hello, Python! "
s.split(",") # [' Hello', ' World! ']
s.strip().startswith("Hello") # True
s.strip().endswith("!") # True
"hello" in s # True
len(s) # 18
",".join(["a","b","c"]) # "a,b,c"
String immutability
Python
s = "hello"
s[0] = "H" # ❌ TypeError: 'str' object does not support item assignment
s = s.capitalize() # ✅ create a new string
Common interview test
"".join(reversed("hello")) returns "olleh" — a common way to reverse a string without slicing. Both approaches are valid.