跳转至

字符串内查找和替换

除了一般的序列操作,字符串还有独有的一些方法。如查找和替换:

print(s.find('in'))
print(s.replace('g', 'gs'))  # 虽然显示字符串已被替换,但实际上是一个新的字符串。

相关的方法见下表:

方法名称 方法说明
endswith(s1: str): bool 如果字符串以指定的字符串结尾,则返回真
startswith(s1: str): bool 如果字符串以指定的字符串开始,则返回真
count(substring): int 返回子字符串在字符串中出现的次数
find(s1): int 返回子字符串在字符串中第一次出现的索引,如果没有,则返回-1
rfind(s1): int 返回子字符串在字符串中最后一次出现的索引,如果没有,则返回-1

示例如下:

>>> s = "welcome to python"
>>> s.endswith("thon")
True
>>> s.startswith("good")
False
>>> s.find("come")
3
>>> s.find("become")
-1
>>> s.rfind("o")
15
>>> s.count("o")
3

最后更新: 2022年10月15日 01:02:48
创建日期: 2022年9月5日 00:56:03
Contributers: Not Committed Yet, yangjh