我想知道是否有任何方法可以让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]
是要走的路。如果不存在冒号或冒号后面没有字符,则结果字符串将为空。