BradTheBrutalitist BradTheBrutalitist - 5 months ago 13
Python Question

Python 3: How Do I Restrict Words From An input() Containing "foo" or "bar"?

How do I make it so if someone types in a word in

input
that contains
"foo"
or
"bar"
in it, it is considered a bad name and they have to try again? This example code that I quickly made up bans only the words
"foo"
and
"bar"
:

while(True):
Input = input("Cool Name Only!:\n")
if(Input.lower() in ['foo', 'bar']):
print("That name is so uncool! Try again.")
else:
print("{0} is a cool name!".format(Input))
break


This code words fine for banning the words
"foo"
and
"bar"
. But what if I wanted to restrict all words with
"foo"
or
"bar"
in it? What if someone types in
"food"
or
bart
? The simple answer would be to ban
"food"
and
"bart"
, right? Well there are probably thousand of words containing
"foo"
or
"bar"
in them, and since it's an input it doesn't have to be a real word. For example someone can type in "Thefoomaster12" or "Mr.bartyboi92". Those names also contain either
"foo"
or
"bar"
in them. How can I do this without having restrict every word containing either
"foo"
or
"bar"
in them? Thanks!

Answer

To check for substrings, we can just use the in keyword. For example:

'foo' in 'seafood'  # True
'foo' in 'flooded'  # False

For a fancy one-liner, we can do something like:

if (any(bad_word in Input.lower() for bad_word in ['foo', 'bar']))