How to slice or extract parts from a string in Python

Published on Aug. 22, 2023, 12:16 p.m.

To slice or extract parts from a string in Python, you can use indexing and slicing. Here are some examples:

s = "Hello, world!"

# use indexing to extract a single character
print(s[0])  # 'H'

# use slicing to extract a substring
print(s[0:5])  # 'Hello'

# use negative indexing to count from the end of the string
print(s[-6:])  # 'world!'

# use slicing with a step to extract every other character
print(s[::2])  # 'Hlo ol!'

# use slicing with a negative step to reverse the string
print(s[::-1])  # '!dlrow ,olleH'

Note that string objects are immutable in Python, so slicing and indexing operations will always create new string objects rather than modifying the original string in place.

Tags:

related content