In [1]: s = "hello world"
In [1]: s = "hello world"
In [2]: s.index("a")
-
ValueError Traceback (most recent call last)
<ipython-input-2-1a10a9a0bcff> in <module>
> 1 s.index("a")
ValueError: substring not found
In [3]: try:
...: s.index("a")
...: except ValueError:
...: pass # or do something else. This means that the character was not found
def check(s, target):
if target in s:
return s.index(target)
else:
return None
s = 'Yeah, I\'m gonna take my horse to the old town road'
check(s, 'g')
# 10
或者使用lambda函数,如果您只想使用它一两次
check = lambda s, t: s.index(t) if t in s else None
s = 'Yeah, I\'m gonna take my horse to the old town road'
check(s, 'old')
# 37
s[37]
# 'o'
您可以使用
try except
捕获抛出的异常:见8.3。处理异常here
试一试就可以了。例如:
如果字符串中存在字符“c”,则返回该字符的索引,如果不存在,则执行指定的操作。。在这种情况下,它将打印“substring not found”并在不中断代码的情况下继续代码
这将与任何错误一起工作。如果您想更具体地针对不同类型的错误执行不同的操作,还可以按错误类型指定操作。。。e、 g
你可以先创建一个函数来检查它
或者使用lambda函数,如果您只想使用它一两次
相关问题 更多 >
编程相关推荐