在 Python 中,字符串切片是一种强大的操作,它允许我们从字符串中提取特定的部分。以下是关于 Python 字符串切片的高级教学:
string = "Hello, World!"
# 提取从索引 7 到索引 11 的子串(不包括索引 11)
substring = string[7:11]
print(substring)
string = "Hello, World!"
# 从索引 0 开始,提取到索引 5(不包括索引 5)
substring1 = string[:5]
# 从索引 7 开始,提取到字符串末尾
substring2 = string[7:]
print(substring1)
print(substring2)
string = "Hello, World!"
# 从倒数第 6 个字符开始,提取到倒数第 2 个字符(不包括倒数第 2 个字符)
substring = string[-6:-2]
print(substring)
string = "Hello, World!"
# 以步长为 2 提取字符串
substring = string[::2]
print(substring)
string = "Hello, World!"
reversed_string = string[::-1]
print(reversed_string)
string = "Hello, World!"
# 先将字符串转换为大写,然后提取前 5 个字符
upper_case_string = string.upper()
substring = upper_case_string[:5]
print(substring)
本文转自:https://www.wodianping.com/app/2024-10/48238.html
标签:substring,string,索引,Python,编程,切片,print,字符串,World From: https://www.cnblogs.com/wodianpingcom/p/18451347