将断言用于控制流 [英] Use assert for control flow
问题描述
我正在尝试检查单词是否带有尾部分号。我在长字符串中找到单词的位置,我想检查单词单词开头+单词长度
处的字符是否为:
。可能是单词是字符串中的最后一个单词,因此尝试获取下一个字符将引发 IndexException
I am trying to check if a word has a trailing semicolon. I have the position of the word within a long string, and I want to check if the character at the position start of word + length of word
is a :
. It can be that the word is the last word in the string, and therefore trying to get the next char will raise an 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
Not what it is normally considered 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
有点有点奇怪,提取然后嵌套。而且我必须做一些技巧来避免代码重复
Looks a little bit weird, to extract and then nested. And I have to do a little trick to avoid the code duplication
3)尝试除分号提取和断言以确保它是分号
semicolon_pos = pos_word + len(word) # Possible position
try:
assert long_string[semicolon_pos] == ':'
# do something
except (IndexError, AssertionError):
# do something else
结构更平整,很容易阅读,但是我有滥用特例的感觉。
Structure is flatter and it is easily read, but I have the feeling that is abusing exceptions usage.
该怎么办蟒蛇人说?
预先表示感谢。
What do the python folks say? thanks in advance.
推荐答案
最简单的方法是将切片用作下标。切片不会抛出IndexError:
The simplest way is just to use a slice as a subscript. Slices don't throw IndexError:
semicolon_pos = pos_word + len(word) # Possible position
if long_string[semicolon_pos:semicolon_pos+1] == ':':
# Do something
else:
# do something else
这篇关于将断言用于控制流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!