字符串检查Python

时间:2013-06-16 13:39:17

标签: string python-3.x

我有一个表示文件名的字符串,如何在几个条件下一次检查?我试过了

if r'.jpg' or r'.png' not in singlefile:

但一直都是误报。

4 个答案:

答案 0 :(得分:3)

您的代码与以下内容相同:

if (r'.jpg') or (r'.png' not in singlefile):

你可能正在寻找:

if r'.jpg' not in singlefile or r'.png' not in singlefile:

或者

if any(part not in singlefile for part in [r'.jpg', r'.png']):

感谢Tim Pietzcker:

  

他(你)实际上(可能)想要

if not any(singlefile.endswith(part) for part in [r'.jpg', r'.png'])
#                     ^^^^^^^^

答案 1 :(得分:2)

这是因为优先权。以下代码意味着。

# r'.jpg' is constant
if r'.jpg' or (r'.png' not in singlefile):

如果不变,或.png不在singlefile。由于常数总是正确的,因此表达总是真实的。

相反,您可以尝试使用正则表达式来检查符合模式的任何字符串。

import re
if re.match(r"\.(?:jpg|png)$", singlefile):

答案 2 :(得分:1)

你的问题在于你的逻辑OR正在检查常量和变量。

r'.png'

将始终评估为True,从而使您的or也成立。

你必须检查两者,如此

if r'.png' not in singlefile or 'r.jpg'  not in singlefile:
    #do stuff

答案 3 :(得分:0)

试试这个:

if r'.jpg' not in singlefile or r'.png' not in singlefile: