python 截取字符串
在 Python 中,可以使用切片(slice)来截取字符串。切片使用中括号 [] 来表示,格式为 [start:stop:step],其中 start 表示起始位置(包括该位置),stop 表示结束位置(不包括该位置),step 表示步长(默认为 1)。
例如,假设有一个字符串 s = "Hello, world!",要截取其中的 "world":
s = "Hello, world!"
sliced = s[7:12]
print(sliced) # 输出:world
如果要从字符串的开头开始截取,可以省略 start;如果要截取到字符串的结尾,可以省略 stop;如果要截取每隔一定步长的字符,可以指定 step。
例如,截取字符串中的前三个字符:
s = "Hello, world!"
sliced = s[:3]
print(sliced) # 输出:Hel
截取字符串中每隔两个字符的字符:
s = "Hello, world!"
sliced = s[::2]
print(sliced) # 输出:Hlo ol!
``
原文地址: https://www.cveoy.top/t/topic/ftdh 著作权归作者所有。请勿转载和采集!