Python multiple comparisons style?

杀马特。学长 韩版系。学妹 提交于 2021-02-04 12:27:22

问题


I am wondering if there is a way to do the following in a more compact style:

if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"):
    do_something()

The problem is i have more than just 4 comparisons in the if statement and it's starting to look rather long, ambiguous, and ugly. Any ideas?


回答1:


How about this:

if text in ( 'Text1', 'Text2', 'Text3', 'Text4' ):
    do_something()

I've always found that simple and elegant.




回答2:


The "if text in" answer is good, but you might also think about the re (regular expressions) package if your text strings fit a pattern. For example, taking your example literally, "Text" followed by a digit would be a simple regular expression.

Here's an example that should work for "Text" followed by a digit. the \Z matches the end of the string, the \d a digit.

if re.match('Text\d\Z', text):
   do_something()


来源:https://stackoverflow.com/questions/5354048/python-multiple-comparisons-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!