任务:检索子串所在的所有位置

检索子串出现位置 - find()

  • find() 用于检测字符串中是否包含子串 ,如果指定 startend 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回 -1。
  • find() 语法:str.find(sub, start, end)
  • sub – 指定搜索的子串
  • start– 开始索引,默认为0
  • end – 结束索引,默认为字符串的长度
# 检索子串所在的所有位置

ip_address = '192.168.1.1'
position = ip_address.find('.')

while position != -1:
    print('.出现位置:{}'.format(position))
    position = ip_address.find('.', position + 1)

print('总共出现{}次'.format(ip_address.count('.')))

输出结果:

.出现位置:3
.出现位置:7
.出现位置:9
总共出现3
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐