要查找子字符串在字符串中的位置索引,可以使用字符串的find()
方法或者index()
方法。
使用find()
方法:
s = "Hello, World!"
sub = "World"
index = s.find(sub)
print(index) # 输出 7
使用index()
方法:
s = "Hello, World!"
sub = "World"
index = s.index(sub)
print(index) # 输出 7
如果子字符串不在原始字符串中,find()
方法会返回-1,而index()
方法会抛出一个ValueError
异常。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:python怎么查找子字符串出现的位置