Python 测试单个字符串中的多个子字符串?
守则的目的:Python 测试单个字符串中的多个子字符串?,python,substring,Python,Substring,守则的目的: 要求用户键入文件名 如果该文件名包含某些子字符串,则该文件名无效。程序“拒绝”并请求一个新的文件名 如果文件名不包含这些子字符串,则该文件名有效,并且程序“接受”它 尝试1: while True: filename = raw_input("Please enter the name of the file:") if "FY" in filename or "FE" in filename or "EX1" in filename or "EX2" in fi
while True:
filename = raw_input("Please enter the name of the file:")
if "FY" in filename or "FE" in filename or "EX1" in filename or "EX2" in filename:
print "Sorry, this filename is not valid."
else:
print "This filename is valid"
break
(为了保持示例的干净性,我省略了输入上的案例检查)
我的问题是将多个子字符串与输入文件名进行比较。我希望将所有子字符串保留在一个元组中,而不是有一个巨大的if或行。我想,如果需要,接管代码的人将更容易找到并添加到元组中,而不必扩展条件语句
尝试2(带元组):
但是我觉得第二次尝试不是实现我想要的东西的最好的方式?我希望尽可能避免for
循环和valid
布尔值
有没有办法让第二次尝试更紧凑?或者我应该返回尝试1吗?尝试:
if any(x in filename for x in BAD_SUBSTRINGS):
这个怎么样
BAD_SUBSTRINGS = ("FY", "FE", "EX1","EX2")
while True:
filename = raw_input("Please enter the name of the file:")
if any(b in filename for b in BAD_SUBSTRINGS):
print("Sorry, this filename is not valid")
else:
print("This filename is valid")
break
谢谢我不知道“任何”关键字。我现在要读一下。在那里查看all
关键字:-)和raiamatrix:any
不是关键字,它是一个内置函数。
BAD_SUBSTRINGS = ("FY", "FE", "EX1","EX2")
while True:
filename = raw_input("Please enter the name of the file:")
if any(b in filename for b in BAD_SUBSTRINGS):
print("Sorry, this filename is not valid")
else:
print("This filename is valid")
break