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! "
2
3print(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 = 30
3score = 95.678
4
5print(f"My name is {name} and I'm {age}")
6print(f"Score: {score:.2f}")
7print(f"{'Python':>20}") # right-align
8print(f"{'Python':<20}") # left-align
9print(f"{2 ** 10 = }") # debug expression
Output
My name is Alice and I'm 30
Score: 95.68
              Python
Python              
2 ** 10 = 1024

03String Slicing

Extract portions of a string using [start:stop:step] syntax.

Python
1s = "Hello, World!"
2
3print(s[0:5]) # Hello
4print(s[7:]) # World!
5print(s[:5]) # Hello
6print(s[::2]) # Hlo ol!
7print(s[::-1]) # !dlroW ,olleH
Output
Hello
World!
Hello
Hlo ol!
!dlroW ,olleH