python - Test for multiple substrings inside a single string? -
purpose of code:
- ask user type in filename.
- if filename contains substrings, filename invalid. program "rejects" , asks new filename.
- if filename not contain substrings, filename valid , program "accepts" it.
attempt 1:
while true: filename = raw_input("please enter name of file:") if "fy" in filename or "fe" in filename or "ex1" in filename or "ex2" in filename: print "sorry, filename not valid." else: print "this filename valid" break
(i'm leaving out case-checking on input keep examples clean).
my issue comes comparing multiple substrings against input filename. wanted keep of substrings in tuple instead of having huge if or
line. figured way easier whoever takes on code find , add tuple if need be, instead of having extend conditional statement.
attempt 2 (with tuple):
bad_substrings = ("fy", "fe", "ex1","ex2") while true: valid = true filename = raw_input("please enter name of file:") substring in bad_substrings: if substring in filename: valid = false break if not valid: print "sorry, filename not valid" else: print "this filename valid" break
but feel attempt 2 isn't pythonic way of accomplishing want? avoid for
loop , valid
boolean if @ possible.
is there way make attempt 2 more compact? or should go attempt 1?
how this?
bad_substrings = ("fy", "fe", "ex1","ex2") while true: filename = raw_input("please enter name of file:") if any(b in filename b in bad_substrings): print("sorry, filename not valid") else: print("this filename valid") break
Comments
Post a Comment