python string.find
时间: 2023-04-17 10:01:06 浏览: 68
Python中的字符串方法find()用于在字符串中查找子字符串,并返回其第一次出现的索引。如果子字符串未找到,则返回-1。
例如:
s = "hello world"
print(s.find("world")) # 输出6
print(s.find("python")) # 输出-1
相关问题
python中string.find用法
在 Python 中,`.find()` 是字符串方法,用于查找子字符串在字符串中的位置。它的语法如下:
```python
str.find(sub[, start[, end]])
```
其中:
- `str` 是要查找的字符串;
- `sub` 是要查找的子字符串;
- `start` 是可选参数,指定开始查找的位置,默认为 0;
- `end` 是可选参数,指定结束查找的位置,默认为字符串的长度。
该方法返回子字符串在字符串中第一次出现的位置,如果没有找到则返回 -1。
例如:
```python
str = "hello world"
print(str.find("world")) # 输出:6
print(str.find("Python")) # 输出:-1
```
如果指定了 `start` 和 `end` 参数,则只在指定的区间中查找子字符串。
例如:
```python
str = "hello world"
print(str.find("o", 3)) # 从索引3开始查找,输出:4
print(str.find("o", 3, 6)) # 在索引3到6之间查找,输出:4
```
Python re.findall
The `re.findall()` function is a method in Python's built-in `re` module used to search for all non-overlapping occurrences of a regular expression pattern in a given string and return a list of all matched substrings.
The syntax of `re.findall()` is as follows:
```python
re.findall(pattern, string, flags=0)
```
Here, `pattern` is the regular expression pattern to search for, `string` is the input string to search in, and `flags` (optional) is an integer value that can modify the behavior of the regular expression pattern.
The `re.findall()` function returns a list containing all the matched substrings in the order they were found in the input string. If there are no matches, an empty list is returned.
Example usage:
```python
import re
text = "The quick brown fox jumps over the lazy dog"
matches = re.findall(r"\b\w{3}\b", text)
print(matches)
# Output: ['The', 'fox', 'the', 'dog']
```
In this example, the regular expression pattern `\b\w{3}\b` searches for all three-letter words in the input string `text`. The `re.findall()` function returns a list of all matched substrings, which are the words "The", "fox", "the", and "dog".