python判断字符串是否含有
时间: 2023-11-21 19:45:02 浏览: 41
在Python中,判断字符串是否包含另一个字符串有多种方法。一种方法是使用正则表达式,但对于这个需求来说,正则表达式有点大材小用。另一种方法是使用count()方法,只要count()方法返回的结果大于0,就说明子串存在于字符串中。还有一种方法是使用operator模块中的contains()方法,它可以很方便地判断子串是否在字符串中。
下面是几种不同的方法示例:
1. 使用正则表达式:
```python
import re
def is_in(full_str, sub_str):
if re.findall(sub_str, full_str):
return True
else:
return False
print(is_in("hello,python", "llo")) # True
print(is_in("hello,python", "lol")) # False
```
2. 使用count()方法:
```python
def is_in(full_str, sub_str):
return full_str.count(sub_str) > 0
print(is_in("hello,python", "llo")) # True
print(is_in("hello,python", "lol")) # False
```
3. 使用operator模块的contains()方法:
```python
import operator
print(operator.contains("hello,python", "llo")) # True
print(operator.contains("hello,python", "lol")) # False
```