Python怎么查找子字符串在字符串中的位置索引

22次阅读
没有评论

共计 264 个字符,预计需要花费 1 分钟才能阅读完成。

要查找子字符串在字符串中的位置索引,可以使用字符串的 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 异常。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-03-19发表,共计264字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)