andraiamatrix andraiamatrix -4 years ago 144
Python Question

Test for multiple substrings inside a single string?

Purpose of the code:


  1. Ask the user to type in a filename.

  2. If that filename contains certain substrings, then that filename is invalid. The program "rejects" and asks for a new filename.

  3. If filename does not contain those substrings, then the filename is valid and the program "accepts" it.



Attempt 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 filename:
print "Sorry, this filename is not valid."
else:
print "This filename is valid"
break


(I'm leaving out the case-checking on the input just to keep the examples clean).

My issue comes with comparing the multiple substrings against the input filename. I wanted to keep all of the substrings in a tuple instead of having a huge
if or
line. I figured that way it would be easier for whoever takes over the code to find and add to the tuple if need be, instead of having to extend the conditional statement.

Attempt 2 (with tuple):

BAD_SUBSTRINGS = ("FY", "FE", "EX1","EX2")

while True:
valid = True
filename = raw_input("Please enter the name of the file:")

for substring in BAD_SUBSTRINGS:
if substring in filename:
valid = false
break

if not valid:
print "Sorry, this filename is not valid"
else:
print "This filename is valid"
break


But I feel like Attempt 2 isn't the most pythonic way of accomplishing what I want? I would like to avoid the
for
loop and the
valid
boolean if at all possible.

Is there some way I could make Attempt 2 more compact? Or should I just go back to Attempt 1?

Answer Source

How about this?

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download