python字符串查与索引的函数
在Python中,可以使用以下字符串查和索引的函数:
1. `find(sub[, start[, end]])`: 查子字符串sub在字符串中的索引位置,如果到返回第一个匹配的索引位置,如果未到返回-1。参数`start`和`end`可以指定查的起始和结束位置,默认为整个字符串。
python index函数
```python
string = "Hello World!"
print(string.find("World"))  # 输出: 6
print(string.find("Python"))  # 输出: -1
```
2. `index(sub[, start[, end]])`: 与find()函数类似,但如果未到子字符串sub,则会引发一个ValueError异常。
```python
string = "Hello World!"
print(string.index("World"))  # 输出: 6
# print(string.index("Python"))  # 引发ValueError异常
```
3. `count(sub[, start[, end]])`: 统计子字符串sub在字符串中出现的次数。参数`start`和`end`可以指定统计的起始和结束位置,默认为整个字符串。
```python
string = "Hello World!"
unt("l"))  # 输出: 3
```
4. `startswith(prefix[, start[, end]])`: 检查字符串是否以指定的前缀开头。参数`start`和`end`可以指定检查的起始和结束位置,默认为整个字符串。
```python
string = "Hello World!"
print(string.startswith("Hello"))  # 输出: True
print(string.startswith("World"))  # 输出: False
```
5. `endswith(suffix[, start[, end]])`: 检查字符串是否以指定的后缀结尾。参数`start`和`end`可以指定检查的起始和结束位置,默认为整个字符串。
```python
string = "Hello World!"
dswith("World!"))  # 输出: True
dswith("Hello"))  # 输出: False
```
这些函数可以帮助你在字符串中进行查、统计和判断操作。