python 查找字符串

2023-03-07 00:00:00 python 字符串 查找

在Python中,有几种方式可以查找字符串,包括使用in关键字、find()方法和index()方法。

1、使用in关键字查找字符串
使用in关键字可以判断一个字符串是否包含另一个字符串。例如:

str1 = 'Hello World'
if 'World' in str1:
    print('Found')
else:
    print('Not found')

在上面的代码中,'World' in str1判断字符串str1中是否包含字符串'World',如果包含,则输出Found,否则输出Not found。

2、使用find()方法查找字符串
使用find()方法可以在一个字符串中查找指定的子串,如果找到了则返回子串第一次出现的位置,否则返回-1。例如:

str1 = 'Hello World'
pos = str1.find('World')
if pos != -1:
    print(f'Found at position {pos}')
else:
    print('Not found')

在上面的代码中,str1.find('World')查找字符串str1中第一次出现的子串'World',如果找到了则返回位置,否则返回-1。

3、使用index()方法查找字符串
和find()方法类似,index()方法也可以在一个字符串中查找指定的子串,但如果找不到则会抛出ValueError异常。例如:

str1 = 'Hello World'
try:
    pos = str1.index('World')
    print(f'Found at position {pos}')
except ValueError:
    print('Not found')

在上面的代码中,str1.index('World')查找字符串str1中第一次出现的子串'World',如果找到了则返回位置,否则抛出ValueError异常,需要用try语句处理。

相关文章