python怎么用find查找字符串

31次阅读
没有评论

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

在 Python 中,可以使用字符串的 find() 方法来查找子字符串。find() 方法返回子字符串在原始字符串中的索引,如果找不到,则返回 -1。
下面是使用 find() 方法查找子字符串的示例代码:

# 原始字符串
string = "Hello, world!"
# 查找子字符串
index = string.find("world")
# 输出结果
if index != -1:
print("子字符串'world'在原始字符串中的索引为", index)
else:
print("未找到子字符串")

输出结果:

 子字符串 'world' 在原始字符串中的索引为 7

在上面的示例中,find() 方法查找子字符串 “world” 在原始字符串 “Hello, world!” 中的索引。由于子字符串存在,因此返回值为 7。

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

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