Code-10
Python find() method
description
The Python find() method detects whether the string contains the substring str. If you specify the range of beg (start) and end (end) , then check whether it is included in the specified range , if it contains the substring, return the starting index value, otherwise Returns -1.
grammar
Find() method syntax:
str.find(str, beg=0, end=len(string))
parameter
- str-specifies the string to be retrieved
- beg-start index, default is 0.
- end-end index, the default is the length of the string.
return value
If it contains a substring, return the starting index value, otherwise return -1.
Instance
The following example shows an example of the find() method:
#!/usr/bin/python
str1 = "this is string example....wow!!!"
str2 = "exam"
print(str1.find(str2))
print(str1.find(str2, 10))
print(str1.find(str2, 40))
The output of the above example is as follows:
15
15
-1
str1 = "Life this is string example....wow!!! Python"
start_position = str1.find('this')
end_position = str1.find('wow!!!') + len('wow!!!') # 求出特定字符串的的长度
print(start_position, end_position)
print(str1[start_position: end_position])
# 输出结果
5 37
this is string example....wow!!!
import re
str1 = "Life this is string example....wow!!! Python"
patteren = 'this.*?wow!!!'
layout_re = re.compile(patteren)
result = re.search(layout_re, str1)
print(result)
print(result.group())
# 输出结果:
<re.Match object; span=(5, 37), match='this is string example....wow!!!'>
this is string example....wow!!!
>>>info = 'abca'
>>> print(info.find('a')) # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
0
>>> print(info.find('a',1)) # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
3
>>> print(info.find('3')) # 查找不到返回-1
-1
>>>