如何使用同一块 Python 代码处理异常和特定条件



我想知道是否有任何方法可以让Python在发生某些事情或出现错误时执行相同的代码块。

例如,我正在编写一个函数,该函数能够获取给定字符串中冒号后面的字符,如果 a( 没有号或b( 冒号存在但后面没有字符,我希望它做同样的事情。假设给定字符串中最多有一个冒号。

def split_colon(string):
try:
ans = string.split(":")[1].strip()
return ans
except IndexError or if ans == "":
return "Hmm, not a word is found"

显然,我在上面的代码中得到了SyntaxError。我怎样才能实现我的目标,而不是

def split_colon(string):
try:
ans = string.split(":")[1].strip()
except IndexError:
return "Hmm, not a word is found"
if ans == "":
return "Hmm, not a word is found"
else:
return ans

,哪个会复制相同的代码?

string.partition(':')[2]

是要走的路。如果冒号不存在或冒号后面没有字符,则生成的字符串将为空。

最新更新