1.startswith和endswith的功能
1)startswith判断字符串开始位是否是某成员(元素)。
2)endswith判断字符串结尾是否是某成员(元素)。
2.startswith和endswith的用法
![aca35331a9b3cd9b6db000e6653ac4a2.png](https://img-blog.csdnimg.cn/img_convert/aca35331a9b3cd9b6db000e6653ac4a2.png)
string就是要被处理的字符串。.startswith(item)
就是内置函数。item是想查询匹配的元素。通过这个函数会返回一个布尔值,也就是True或False。
endswith的用法和startswith的用法是一样的。
print('my name is xiaobian'.startswith('my'))
print('my name is xiaobian'.endswith('my'))
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/1.py
True
False
进程已结束,退出代码为 0
3.代码
# coding:utf-8
info = 'this is a string example!!'
result = info.startswith('this')
print(result)
result = info.startswith('this is a string example!!')
print(result)
print(bool(info == 'this is a string example!!'))
result = info.endswith('this is a string example!!')
print('result:',result)
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/swith.py
True
True
True
result: True
进程已结束,退出代码为 0
endswith和startswith也可以对完整(整体)的字符串进行判断。
info.endswith('this is a string example!!')
相当于bool(info == 'this is a string example!!')
,效果是一样的。