python 查找字符串位置
时间: 2023-09-27 09:06:12 浏览: 52
你可以使用字符串的 `find()` 方法来查找子字符串的位置。例如,如果你想查找字符串 `s` 中子字符串 `sub` 的位置,你可以这样做:
```
pos = s.find(sub)
```
如果 `sub` 存在于 `s` 中,那么 `pos` 将是 `sub` 的第一个字符在 `s` 中出现的位置。如果 `sub` 不存在于 `s` 中,那么 `pos` 将是 `-1`。另外,你还可以使用 `index()` 方法来查找子字符串的位置,用法与 `find()` 方法相似,但是如果 `sub` 不存在于 `s` 中,`index()` 方法会抛出一个 `ValueError` 异常。
相关问题
python中查找字符串位置
要查找一个字符串在另一个字符串中的位置,可以使用`find()`方法或者`index()`方法。
`find()`方法:返回第一次出现子字符串的起始位置,如果没有找到则返回-1。
示例代码:
```
str1 = "hello, world!"
str2 = "world"
pos = str1.find(str2)
print(pos)
```
输出结果为:7
`index()`方法:返回第一次出现子字符串的起始位置,如果没有找到则引发ValueError异常。
示例代码:
```
str1 = "hello, world!"
str2 = "world"
try:
pos = str1.index(str2)
print(pos)
except ValueError:
print("not found")
```
输出结果为:7
Python查找字符串
的方法有哪些?
Python查找字符串的方法有以下几种:
1. 使用in关键字判断字符串是否包含子字符串。
2. 使用find()方法查找子字符串,如果找到则返回子字符串的起始位置,否则返回-1。
3. 使用index()方法查找子字符串,如果找到则返回子字符串的起始位置,否则抛出异常。
4. 使用startswith()方法判断字符串是否以指定的子字符串开头。
5. 使用endswith()方法判断字符串是否以指定的子字符串结尾。
6. 使用正则表达式匹配字符串中的子串。