迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中 ValueError: substring not found 错误

作者:迹忆客 最近更新:2022/10/29 浏览次数:

当我们将字符串中不存在的值传递给 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')

python ValueError substring not found

我们传递给 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')

python 解决valueerr错误

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

python 解决 valueerror 错误

如果字符串中存在子字符串,则返回使用子字符串调用 index() 方法的结果,否则返回 None

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便