Python中find()
时间: 2024-02-16 12:57:48 浏览: 17
在Python中,find()方法用于查找字符串中是否包含指定的子字符串,并返回子字符串第一次出现的索引位置。如果找不到子字符串,则返回-1。
以下是一个示例代码:
```python
str1 = 'hello hello'
print(str1.find('e')) # 输出:1
```
在上面的示例中,我们定义了一个字符串str1,并使用find()方法查找子字符串'e'。由于'e'第一次出现在索引位置1,所以输出结果为1。
需要注意的是,find()方法是从左侧开始查找子字符串。如果要从右侧开始查找,可以使用rfind()方法。
以下是一个使用rfind()方法的示例代码:
```python
str1 = 'hello hello'
print(str1.rfind('e')) # 输出:9
```
在上面的示例中,我们使用rfind()方法查找子字符串'e'。由于'e'最后一次出现在索引位置9,所以输出结果为9。
相关问题
Python中find
函数的用法
在Python中,find函数是字符串类型的内置函数。它用于在字符串中查找指定的子字符串,并返回其第一次出现的位置。如果找不到子字符串,则返回-1。
语法:
str.find(sub[, start[, end]])
参数说明:
- sub:要查找的子字符串。
- start:查找的起始位置,默认为0。
- end:查找的结束位置,默认为字符串的长度。
示例:
```python
str = "Hello World"
print(str.find("World")) # 输出 6
print(str.find("Python")) # 输出 -1
```
在上面的示例中,str.find("World")返回6,因为子字符串"World"在原始字符串中的位置是从索引6开始的。而str.find("Python")返回-1,因为原始字符串中不存在"Python"子字符串。
python中find函数
在Python中,find()是一种字符串方法,用于在字符串中查找指定的子字符串。它返回子字符串第一次出现的位置,如果没有找到,则返回-1。
例如,以下代码查找字符串s中是否包含子字符串"hello":
```
s = "Python is a great language"
if s.find("hello") != -1:
print("Found 'hello' in the string")
else:
print("Did not find 'hello' in the string")
```
输出结果应该是:"Did not find 'hello' in the string"。
可以通过指定可选参数start和end来限制搜索的范围。例如,以下代码查找字符串s中从第7个字符开始到第12个字符结束的子字符串"great":
```
s = "Python is a great language"
if s.find("great", 7, 12) != -1:
print("Found 'great' in the string")
else:
print("Did not find 'great' in the string")
```
输出结果应该是:"Found 'great' in the string"。