字符串截取方法
字符串截取可以使用Python内置的切片操作。例如,要截取字符串s中从第2个字符到第5个字符的子串,可以使用s[1:5],注意Python中下标从0开始计数。
除了切片操作,还可以使用Python内置的字符串方法,如:
-
str.split(sep=None, maxsplit=-1):将字符串按照指定分隔符sep进行分割,返回一个列表。如果不指定分隔符,则默认使用空格作为分隔符。maxsplit用于指定最大分割次数。
-
str.strip(chars=None):去掉字符串左右两边的指定字符,默认去掉空格。
-
str.replace(old, new[, count]):将字符串中的old子串替换为new子串,count用于指定最大替换次数。
-
str.find(sub[, start[, end]]):查找字符串中是否包含子串sub,如果包含则返回第一次出现的位置,否则返回-1。start和end用于指定查找的起始和结束位置,默认为整个字符串。
示例代码:
s = "hello world"
print(s[1:5]) # 输出:ello
s = "hello,world"
print(s.split(",")) # 输出:['hello', 'world']
s = " hello world "
print(s.strip()) # 输出:hello world
s = "hello world"
print(s.replace("o", "a")) # 输出:hella warld
s = "hello world"
print(s.find("wo")) # 输出:6
原文地址: https://www.cveoy.top/t/topic/Fxk 著作权归作者所有。请勿转载和采集!