python全栈开发《22.字符串的startswith和endswith函数》
endswith和startswith也可以对完整(整体)的字符串进行判断。
info.endswith('this is a string example!!')
或info.startswith('this is a string example!!')
相当于bool(info == 'this is a string example!!')
,效果是一样的。
item:你想查询的元素(成员)。通过find函数,会返回一个整型。
index函数和find函数用法一样。但是通过index函数,可能会返回一个整型,也有可能会报错。
print('my name is xiaobian'.find('e'))
print('my name is xioabian'.index('i'))
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/1.py
6
8
进程已结束,退出代码为 0
空格也算一个位置。
# coding:utf-8
info = 'python is a good code'
result = info.find('a')
print(result)
result = info.find('ok')
print(result)
result = info.index('a')
print(result)
result = info.index('ok')
print(result)
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/find.py
Traceback (most recent call last):
File "/Users/llq/PycharmProjects/pythonlearn/pythonlearn1/find.py", line 12, in <module>
result = info.index('ok')
ValueError: substring not found
10
-1
10
进程已结束,退出代码为 1