python中find函数
时间: 2023-11-15 10:05:18 浏览: 38
在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"。
相关问题
python中find函数怎么用
在Python中,find()函数用于在字符串中查找指定的子字符串,并返回子字符串第一次出现的位置。如果找不到子字符串,则返回-1。
find()函数的语法如下:
```python
str.find(sub[, start[, end]])
```
其中,参数sub表示要查找的子字符串;参数start表示查找的起始位置(默认为0);参数end表示查找的结束位置(默认为字符串的长度)。
例如,如果我们有一个字符串s,想要查找其中是否包含子字符串"hello",可以使用以下代码:
```python
s = "hello world"
if s.find("hello") != -1:
print("找到了")
else:
print("没找到")
```
这段代码会输出"找到了",因为字符串s中包含子字符串"hello"。如果我们要查找的子字符串不存在,则会输出"没找到"。
python中find函数的用法
Python中的find函数用于在字符串中查找指定的子字符串,并返回其第一次出现的位置。如果未找到该子字符串,则返回-1。
例如,以下代码将在字符串s中查找子字符串"world":
s = "hello world"
print(s.find("world"))
输出结果为:
6
因为"world"第一次出现在字符串s的第7个位置,而Python中的索引从0开始,所以返回值为6。
需要注意的是,find函数区分大小写,如果要忽略大小写,可以使用lower()或upper()函数将字符串转换为小写或大写后再进行查找。