深度阅读

How to slice or extract parts from a string in Python

作者
作者
2023年08月22日
更新时间
7.11 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。