python全栈开发《22.字符串的startswith和endswith函数》
1.startswith和endswith的功能
- 1)startswith判断字符串开始位是否是某成员(元素)。
- 2)endswith判断字符串结尾是否是某成员(元素)。
2.startswith和endswith的用法
string就是要被处理的字符串。.startswith(item)就是内置函数。item是想查询匹配的元素。通过这个函数会返回一个布尔值,也就是True或False。
endswith的用法和startswith的用法是一样的。
代码语言:javascript代码运行次数:0运行复制print('my name is xiaobian'.startswith('my'))
print('my name is xiaobian'.endswith('my'))
运行结果:
代码语言:javascript代码运行次数:0运行复制/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/1.py
True
False
进程已结束,退出代码为 0
3.代码
代码语言:javascript代码运行次数:0运行复制# 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)
运行结果:
代码语言:javascript代码运行次数:0运行复制/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!!'),效果是一样的。


发布评论