# 示例代码:find在Python中的用法
# find() 方法用于查找子字符串在字符串中的位置,如果找到则返回索引值,否则返回 -1。
# 定义一个字符串
text = "Hello, welcome to my world."
# 查找子字符串 "welcome" 在字符串中的位置
position = text.find("welcome")
print(f"'welcome' 的位置是: {position}") # 输出: 'welcome' 的位置是: 8
# 查找不存在的子字符串 "test"
position_not_found = text.find("test")
print(f"'test' 的位置是: {position_not_found}") # 输出: 'test' 的位置是: -1
# 从指定位置开始查找子字符串 "o"
position_from_index = text.find("o", 5) # 从索引 5 开始查找
print(f"从索引 5 开始,'o' 的位置是: {position_from_index}") # 输出: 从索引 5 开始,'o' 的位置是: 25
# 查找子字符串 "o" 在指定范围内 (起始索引为 5,结束索引为 20)
position_in_range = text.find("o", 5, 20)
print(f"'o' 在索引 5 到 20 之间的位置是: {position_in_range}") # 输出: 'o' 在索引 5 到 20 之间的位置是: 17
上一篇:python获取列表的长度
下一篇:python多线程和多进程的区别
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站