python 字符串部分匹配
时间: 2023-10-08 15:04:02 浏览: 39
在 Python 中,可以使用字符串的 `find()` 方法进行部分匹配。该方法返回指定子串在字符串中第一次出现的位置,如果没有找到则返回 -1。
例如,假设我们有一个字符串 `s` 和一个子串 `sub`,我们可以使用以下代码进行部分匹配:
```python
s = "Hello, world!"
sub = "world"
index = s.find(sub)
if index != -1:
print("'{0}' is found in '{1}' at index {2}".format(sub, s, index))
else:
print("'{0}' is not found in '{1}'".format(sub, s))
```
输出结果为:
```
'world' is found in 'Hello, world!' at index 7
```
注意,`find()` 方法是区分大小写的。如果需要进行不区分大小写的部分匹配,可以将字符串和子串都转换为小写或大写再进行匹配。例如:
```python
s = "Hello, world!"
sub = "WORLD"
index = s.lower().find(sub.lower())
if index != -1:
print("'{0}' is found in '{1}' at index {2}".format(sub, s, index))
else:
print("'{0}' is not found in '{1}'".format(sub, s))
```
输出结果为:
```
'WORLD' is found in 'Hello, world!' at index 7
```