python全栈开发《23.字符串的find与index函数》
1.补充说明上文
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!!'),效果是一样的。
2.find和index的功能
- 1)find和index都是返回你想寻找的成员的位置。
3.find和index的用法
item:你想查询的元素(成员)。通过find函数,会返回一个整型。
index函数和find函数用法一样。但是通过index函数,可能会返回一个整型,也有可能会报错。
代码语言:javascript代码运行次数:0运行复制print('my name is xiaobian'.find('e'))
print('my name is xioabian'.index('i'))
运行结果:
代码语言:javascript代码运行次数:0运行复制/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/1.py
6
8
进程已结束,退出代码为 0
空格也算一个位置。
4.find和index的区别
- 1)如果find找不到元素,会返回-1。
- 2)如果index找不到元素,会导致程序报错。
5.代码
代码语言:javascript代码运行次数: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)
运行结果:
代码语言:javascript代码运行次数:0运行复制/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
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。原始发表:2024-07-30,如有侵权请联系 cloudcommunity@tencent 删除字符串python函数开发全栈

发布评论