使用assert进行控制流程

时间:2014-01-15 08:47:55

标签: python exception control-flow

我正在尝试检查一个单词是否有一个尾随的分号。我在一个长字符串中有该单词的位置,我想检查start of word + length of word位置的字符是否为:。可能是单词是字符串中的最后一个单词,因此尝试获取下一个字符将会引发IndexException

我有三个想法:

1)检查我们是否在字符串的末尾,然后检查它是否不是分号

semicolon_pos = pos_word + len(word) # Possible position
if semicolon_pos < len(long_string) and long_string[semicolon_pos] == ':':
    # do something...
else:
    # do something else

不是通常被认为是pythonic的

2)尝试 - 除分号提取和分号相等

semicolon_pos = pos_word + len(word) # Possible position
try:
   if long_string[semicolon_pos] == ':':
      # Do something
   else:
      # do something else (which is the same as in the except clause)

except IndexError:
    # do something else

看起来有点奇怪,提取然后嵌套。我必须做一个小技巧来避免代码重复

3)尝试 - 除了分号提取和断言以确保它是分号

semicolon_pos = pos_word + len(word) # Possible position
try:
    assert long_string[semicolon_pos] == ':'
    # do something
except (IndexError, AssertionError):
    # do something else

结构更平坦且易于阅读,但我有一种滥用异常使用的感觉。

蟒蛇人说什么? 提前谢谢。

4 个答案:

答案 0 :(得分:3)

绝对滥用断言。原因:当使用-O标志运行代码时,甚至不会执行断言。

使用断言的推荐方法是检查由算法中的错误(后置条件)导致的“不可能”条件。对于前置条件和程序逻辑,应该使用普通的例外。

答案 1 :(得分:2)

(string[index] if index < len(string) else None) == ':'

答案 2 :(得分:1)

我认为这样更容易:

#considering mylongstring contains the word
#+1 for the possible colon
mylongstring[:pos_word + len(word) + 1].endswith(':')

或者,如果长字符串很长,你不想复制太多:

mylongstring[pos_word:pos_word + len(word) + 1][-1] == ':'

答案 3 :(得分:1)

最简单的方法是使用切片作为下标。切片不会抛出IndexError:

semicolon_pos = pos_word + len(word) # Possible position
if long_string[semicolon_pos:semicolon_pos+1] == ':':
   # Do something
else:
   # do something else 
相关问题