如果str.index不存在,则选择第二个选项

2024-04-18 03:16:44 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个str,并且我使用了str.index(char),但是这个字符不存在,那么可以用一行将另一个字符分配给变量吗

也许像这样

str = "bar/foo"

t = str.index("_") | "Empty"

str不包含,因此应该指定字符串“Empty”


Tags: 字符串indexfoobar字符emptycharstr
1条回答
网友
1楼 · 发布于 2024-04-18 03:16:44

由于^{}会在子字符串不在字符串中时抛出ValueError,因此将其包装到if/else中,通过in运算符检查字符串中是否存在子字符串:

>>> s = "bar/foo"
>>> s.index("_") if "_" in s else "Empty"
"Empty"

>>> s = "bar_foo"
>>> s.index("_") if "_" in s else "Empty"
3

相关问题 更多 >