Python 中 ValueError: substring not found 错误
当我们将字符串中不存在的值传递给 str.index()
方法时,会出现 Python “ValueError: substring not found”。 要解决错误,需要改用 find()
方法,例如 my_str.find('z')
,或使用 try/except
块处理错误。
下面是错误产生生的一个示例代码。
my_str = 'apple'
# ⛔️ ValueError: substring not found
idx = my_str.index('z')
我们传递给 index
方法的子字符串不包含在字符串中,这导致了 ValueError
。
解决此问题的一种方法是改用 str.find()
方法。
my_str = 'apple'
idx = my_str.find('z')
print(idx) # 👉️ -1
str.find
方法返回字符串中提供的子字符串第一次出现的索引。
如果在字符串中找不到子字符串,该方法返回 -1。
或者,我们可以在调用 index()
方法之前检查子字符串是否存在于字符串中。
my_str = 'apple'
if 'z' in my_str:
idx = my_str.index('z')
print(idx)
else:
# 👇️ this runs
print('substring is not in string')
in
运算符测试成员资格。 例如,如果 x 是 s 的成员,则 x in s
的计算结果为 True,否则计算结果为 False。
str.index
方法返回字符串中提供的子字符串第一次出现的索引。
如果在字符串中找不到子字符串,该方法将引发 ValueError。
我们还可以使用 try/except
块来处理在字符串中找不到子字符串的情况。
my_str = 'apple'
try:
idx = my_str.index('z')
print(idx)
except ValueError:
# 👇️ this runs
print('substring is not in string')
我们在字符串上调用 index()
方法,如果引发 ValueError
,则运行 except 块。
我们还可以使用单行 if/else
语句。
my_str = 'apple'
result_1 = my_str.index('z') if 'z' in my_str else None
print(result_1) # 👉️ None
result_2 = my_str.index('a') if 'a' in my_str else None
print(result_2) # 👉️ 0
如果字符串中存在子字符串,则返回使用子字符串调用 index()
方法的结果,否则返回 None。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。