python字符串匹配 str.find
时间: 2023-04-23 15:07:46 浏览: 79
str.find是Python中字符串的一个方法,用于在字符串中查找指定子字符串的位置。如果找到了子字符串,则返回其在字符串中的起始位置,否则返回-1。例如:
```
s = "hello world"
print(s.find("world")) # 输出6
print(s.find("python")) # 输出-1
```
在上面的例子中,第一个find方法返回6,因为"world"子字符串在字符串中的起始位置是6;第二个find方法返回-1,因为"python"子字符串在字符串中不存在。
相关问题
Python中str.find用法
在 Python 中,str.find() 方法用于检索字符串中是否包含指定的子字符串,并返回子字符串在原始字符串中第一次出现的位置。如果没有找到该子字符串,则返回-1。其语法如下:
```
str.find(sub, start, end)
```
其中,`sub` 表示要查找的子字符串,`start` 和 `end` 是可选参数,表示查找的起始位置和结束位置,默认值分别为 0 和字符串的长度。
示例:
```python
my_string = "Hello, world!"
print(my_string.find("world")) # 输出 7
print(my_string.find("universe")) # 输出 -1,未找到
```
需要注意的是,str.find() 方法仅返回第一个匹配项的位置。如果需要查找字符串中所有匹配项的位置,可以使用正则表达式或者循环遍历来实现。
python正则匹配re.findall
`re.findall()`是Python中用于正则匹配的函数之一。它的作用是在给定的字符串中查找所有满足正则表达式模式的非重叠匹配,并以列表的形式返回这些匹配结果。
以下是一个使用`re.findall()`函数的例子:
```python
import re
str = 'aabpythonbaregexa,aabpythonbacoola'
pattern = r'a(.*?)a' # 匹配以'a'开头和结尾的内容
result = re.findall(pattern, str)
print(result) # 输出:['abpythonb', 'abpythonb']
```
在上面的例子中,我们使用正则表达式模式`r'a(.*?)a'`来匹配字符串`str`中以'a'开头和结尾的内容。`re.findall()`函数返回了所有满足这个模式的非重叠匹配,即`['abpythonb', 'abpythonb']`。
需要注意的是,`re.findall()`函数返回的是一个列表,其中每个元素都是一个匹配结果。如果没有找到任何匹配,返回的列表将为空。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)