用python实现find函数
时间: 2024-05-12 18:15:43 浏览: 16
`find()`函数是用于在字符串中查找子字符串的方法,如果找到,则返回子字符串的起始索引,否则返回-1。以下是用Python实现`find()`函数的示例代码:
```python
def find(string, substring):
"""
在string中查找substring的位置,返回找到的第一个位置的索引值
如果没有找到,则返回-1。
"""
n = len(string)
m = len(substring)
for i in range(n - m + 1):
if string[i:i + m] == substring:
return i
return -1
```
使用示例:
```python
string = "hello world"
substring = "world"
print(find(string, substring)) # 6
substring = "python"
print(find(string, substring)) # -1
```
相关问题
python爬虫find函数
在Python中,爬虫是指通过编写程序来自动获取互联网上的数据。而find函数是Python中字符串的一个方法,用于查找子字符串在原字符串中的位置。
具体来说,find函数的语法如下:
```
str.find(sub[, start[, end]])
```
其中,str是原字符串,sub是要查找的子字符串,start和end是可选参数,用于指定查找的起始位置和结束位置。
find函数会返回子字符串在原字符串中第一次出现的位置,如果找不到则返回-1。需要注意的是,find函数是区分大小写的。
下面是一个示例:
```python
str = "Hello, world!"
index = str.find("world")
print(index) # 输出:7
```
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"。如果我们要查找的子字符串不存在,则会输出"没找到"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)