在Python 3中,查找字符串通常使用`str.find()`方法。以下是`find()`方法的基本用法:
```python
str.find(sub[, start[, end]])
`str`:被搜索的原始字符串。
`sub`:要查找的子字符串。
`start`:搜索的起始索引,默认为0。
`end`:搜索的结束索引,默认为字符串的长度。
`find()`方法返回子字符串在原始字符串中首次出现的位置索引,如果子字符串不存在,则返回-1。
下面是一些示例代码:
```python
示例1:查找子字符串在字符串中的位置
text = "Hello, world!"
substring = "world"
index = text.find(substring)
print(index) 输出:7
示例2:查找子字符串在字符串中的位置,指定起始索引
text = "Hello, world!"
substring = "world"
start_index = 7
index = text.find(substring, start_index)
print(index) 输出:7
示例3:查找子字符串在字符串中的位置,指定起始和结束索引
text = "Hello, world!"
substring = "world"
start_index = 7
end_index = 12
index = text.find(substring, start_index, end_index)
print(index) 输出:7
示例4:查找子字符串在字符串中是否存在
text = "Hello, world!"
substring = "planet"
index = text.find(substring)
if index != -1:
print(f"Substring found at index {index}")
else:
print("Substring not found") 输出:Substring not found
另外,你还可以使用`in`关键字来检查一个子字符串是否存在于字符串中,例如:
```python
text = "Hello, world!"
substring = "planet"
if substring in text:
print("Substring found")
else:
print("Substring not found") 输出:Substring not found
需要注意的是,`in`关键字进行查找时,它会从左到右在整个字符串中查找子字符串,而`find()`方法同样可以指定查找的起始和结束位置。