欢迎访问宙启技术站
智能推送

contains()函数检查字符串是否包含子字符串?

发布时间:2023-06-20 23:44:17

Python中,contains()函数并不是一个内置函数,但是Python中的字符串类型确实有一个内置的函数叫做__contains__();该函数用来判断当前字符串中是否包含指定的子字符串。

例如:

s = 'hello, world!'
if 'world' in s:
    print('s contains "world"')

该例子中,'world'是一个子字符串,而s.__contains__('world')则返回True,因此打印输出"s contains "world""。

需要注意的是,如果使用in操作符判断字符串是否包含一个子字符串,那么Python会自动调用__contains__()函数。因此,上述代码可以简化为:

s = 'hello, world!'
if 'world' in s:
    print('s contains "world"')

这段代码和 个例子的输出结果是一样的。

除此之外,还可以使用find()和index()函数来判断字符串是否包含子字符串。

s = 'hello, world!'
if s.find('world') != -1:
    print('s contains "world"')

s = 'hello, world!'
try:
    i = s.index('world')
    print('s contains "world" at index', i)
except ValueError:
    print('s does not contain "world"')

这两个函数的区别在于,当字符串不包含指定的子字符串时,find()函数会返回-1,而index()函数会抛出ValueError异常。因此,在使用index()函数时,应该使用try-except语句来捕获异常。在大多数情况下,使用in操作符是最简单和最安全的判断字符串是否包含子字符串的方式。