在Python中,`find()`方法用于查找子字符串在原始字符串中的位置。以下是`find()`方法的基本用法:
string.find(substring, start=0, end=len(string))
参数说明:
`substring`:要在`string`中查找的子字符串。
`start`:开始搜索的位置,默认为0。
`end`:搜索结束的位置,默认为字符串的长度。
返回值:
如果找到子字符串,返回子字符串在原始字符串中首次出现的索引。
如果未找到子字符串,返回-1。
示例代码:
示例字符串
text = "Hello, world!"
查找子字符串 "world"
index = text.find("world")
输出结果
if index != -1:
print(f"子字符串 'world' 在原始字符串中的索引为 {index}")
else:
print("未找到子字符串")
输出结果:子字符串 'world' 在原始字符串中的索引为 7
你还可以指定查找的起始和结束位置:
查找子字符串 "world",从索引5开始到字符串末尾
index = text.find("world", 5)
输出结果
if index != -1:
print(f"子字符串 'world' 在原始字符串中的索引为 {index}")
else:
print("未找到子字符串")
输出结果:子字符串 'world' 在原始字符串中的索引为 7
需要注意的是,`find()`方法返回的索引是从0开始的。