python怎么用find查找字符串

1157
2023/10/1 16:08:27
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 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。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python百万并发数据怎么处理