> 技术文档 > python语法笔记之-字符串 index() 方法语法详解

python语法笔记之-字符串 index() 方法语法详解


问题1:字符串 index() 方法语法详解

问题代码

str1 = \"Hello,Python\";str2 = \"Python\";print(str1.index(str2));

语法详解

1. str.index() 方法基本语法
str.index(sub[, start[, end]])

参数说明:

  • sub: 要查找的子字符串
  • start: 可选参数,开始查找的位置(默认为0)
  • end: 可选参数,结束查找的位置(默认为字符串长度)

返回值:

  • 返回子字符串在原字符串中第一次出现的索引位置
  • 如果找不到子字符串,会抛出 ValueError 异常
2. 代码执行过程分析
str1 = \"Hello,Python\" # 原字符串str2 = \"Python\" # 要查找的子字符串print(str1.index(str2)) # 输出:7

执行步骤:

  1. str1 包含字符串 \"Hello,Python\"
  2. str2 包含字符串 \"Python\"
  3. str1.index(str2)str1 中查找 str2 第一次出现的位置
  4. \"Python\"\"Hello,Python\" 中从索引7开始出现
  5. 输出结果:7
3. 字符串索引位置说明
字符串: \"Hello,Python\"索引: 012345678901
  • \"Python\" 从索引7开始,到索引12结束
  • 所以 index() 返回第一个字符 \'P\' 的位置:7
4. 相关方法对比
方法 功能 找不到时的行为 index() 查找子字符串位置 抛出 ValueError find() 查找子字符串位置 返回 -1 rindex() 从右向左查找 抛出 ValueError rfind() 从右向左查找 返回 -1
5. 实际应用示例
# 基本用法text = \"Hello, World!\"print(text.index(\"World\")) # 输出:7# 指定搜索范围text = \"Hello, World! Hello, Python!\"print(text.index(\"Hello\", 1)) # 从索引1开始查找,输出:14# 错误处理try: text = \"Hello, World!\" position = text.index(\"Python\") print(f\"找到位置:{position}\")except ValueError: print(\"未找到子字符串\")# 使用 find() 方法(推荐)text = \"Hello, World!\"position = text.find(\"Python\")if position != -1: print(f\"找到位置:{position}\")else: print(\"未找到子字符串\")
6. 注意事项
  1. 区分大小写index() 方法区分大小写

    text = \"Hello, World!\"print(text.index(\"world\")) # ValueError: substring not found
  2. 只返回第一次出现的位置:如果有多个相同的子字符串,只返回第一个

    text = \"Hello, Hello, World!\"print(text.index(\"Hello\")) # 输出:0(不是7)
  3. 空字符串:空字符串在任何位置都能找到

    text = \"Hello\"print(text.index(\"\")) # 输出:0
  4. 建议使用 find() 方法find() 方法更安全,不会抛出异常

    text = \"Hello, World!\"position = text.find(\"Python\") # 返回 -1,不会抛出异常