beginnerData Types
Strings In Depth
String methods, formatting, f-strings, and common operations.
01String Methods
Python strings come with many built-in methods for manipulation.
Python
1text = " Hello, Python! "23print(text.strip()) # "Hello, Python!"4print(text.lower()) # " hello, python! "5print(text.upper()) # " HELLO, PYTHON! "6print(text.replace("Python", "World"))7print(text.split(",")) # [' Hello', ' Python! ']8print(text.find("Python")) # 9
Output
Hello, Python! hello, python! HELLO, PYTHON! Hello, World! [' Hello', ' Python! '] 9
02F-Strings (Formatted String Literals)
The modern way to format strings in Python 3.6+:
Python
1name = "Alice"2age = 303score = 95.67845print(f"My name is {name} and I'm {age}")6print(f"Score: {score:.2f}")7print(f"{'Python':>20}") # right-align8print(f"{'Python':<20}") # left-align9print(f"{2 ** 10 = }") # debug expression
Output
My name is Alice and I'm 30
Score: 95.68
Python
Python
2 ** 10 = 102403String Slicing
Extract portions of a string using [start:stop:step] syntax.
Python
1s = "Hello, World!"23print(s[0:5]) # Hello4print(s[7:]) # World!5print(s[:5]) # Hello6print(s[::2]) # Hlo ol!7print(s[::-1]) # !dlroW ,olleH
Output
Hello World! Hello Hlo ol! !dlroW ,olleH