Linux 拨号vps windows公众号手机端

string怎么查找子字符串

lewis 8年前 (2017-09-25) 阅读数 8 #程序编程
文章标签 String

在Python中,可以使用字符串的find()方法来查找子字符串。find()方法返回子字符串在父字符串中第一次出现的索引位置。如果子字符串不存在,则返回-1。

以下是一个示例:

string = "Hello, world!"
sub_string = "world"

index = string.find(sub_string)
print(index)  # 输出: 7

你可以使用find()方法来查找字符串中的多个子字符串。以下是一个示例:

string = "Hello, world!"
sub_string1 = "Hello"
sub_string2 = "world"

index1 = string.find(sub_string1)
index2 = string.find(sub_string2)

print(index1)  # 输出: 0
print(index2)  # 输出: 7

另外,还可以使用index()方法来查找子字符串。index()方法与find()方法类似,但是如果子字符串不存在,则会抛出ValueError异常。

以下是一个使用index()方法的示例:

string = "Hello, world!"
sub_string = "world"

try:
    index = string.index(sub_string)
    print(index)
except ValueError:
    print("子字符串不存在")

这些方法可以帮助你在字符串中查找子字符串。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门