Sym*_*mon 8 python comparison coding-style readability
我想知道是否有办法以更紧凑的方式执行以下操作:
if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"):
do_something()
Run Code Online (Sandbox Code Playgroud)
问题是我在if语句中只有4个比较,它开始看起来很长,模糊和丑陋.有任何想法吗?
Chr*_*ips 16
这个怎么样:
if text in ( 'Text1', 'Text2', 'Text3', 'Text4' ):
do_something()
Run Code Online (Sandbox Code Playgroud)
我总是发现那简单而优雅.
"if in text"答案很好,但如果文本字符串符合模式,您也可以考虑re(正则表达式)包.例如,从字面上看你的例子,"Text"后跟一个数字将是一个简单的正则表达式.
这是一个应该适用于"Text"后面跟一个数字的例子.\ Z匹配字符串的末尾,\ da数字.
if re.match('Text\d\Z', text):
do_something()
Run Code Online (Sandbox Code Playgroud)