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
执行步骤:
str1
包含字符串\"Hello,Python\"
str2
包含字符串\"Python\"
str1.index(str2)
在str1
中查找str2
第一次出现的位置\"Python\"
在\"Hello,Python\"
中从索引7开始出现- 输出结果:
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. 注意事项
-
区分大小写:
index()
方法区分大小写text = \"Hello, World!\"print(text.index(\"world\")) # ValueError: substring not found
-
只返回第一次出现的位置:如果有多个相同的子字符串,只返回第一个
text = \"Hello, Hello, World!\"print(text.index(\"Hello\")) # 输出:0(不是7)
-
空字符串:空字符串在任何位置都能找到
text = \"Hello\"print(text.index(\"\")) # 输出:0
-
建议使用
find()
方法:find()
方法更安全,不会抛出异常text = \"Hello, World!\"position = text.find(\"Python\") # 返回 -1,不会抛出异常