Python Forum

Full Version: Basic input() function question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

Started programming for the first time using Python and I've gotten through all the basics and practicing putting everything together. I love it so far. A quick question for anyone that can help.

I'd like it so that when I ask a user to give input, the script will detect a certain string of letters that are inappropriate.

For example, this would be useful for asking a player what they would like to name their character (like in a text/mud game). Here's what I have so far and it works well enough:
------------------
print("Please tell me the name of the character you wish to create.\"")
confirmed = False
while not confirmed:
name = input()
while name == '' or not name.isalpha() or len(name) >=25 or len(name) <3:
print("\tSorry, you must pick a more appropriate name.")
print("Your name must not be blank, must be alphabetical only (no numbers)...")
print("and must be between 3 and 25 characters.")
print('')
print("Please tell me the name of the character you wish to create.")
name = input()
-------------------

So I'd also like to include in the code whether the input() includes banned words/syllables like 'ass' or 'shit' etc, and reject the name. Any help would be greatly appreciated!

print("A sage comes up to you.  He says, \"Greetings, Adventurer!  Please tell me the name of the character you wish to create.\"")
confirmed = False
while not confirmed:
    name = input()
    while name == '' or not name.isalpha() or len(name) >=25 or len(name) <3:
        print("\tSorry, you must pick a more appropriate name.")
        print("Bear in mind, your name must not be blank, must be alphabetical only (no numbers)...")
        print("and must be between 3 and 25 characters.")
        print('')
        print("Please tell me the name of the character you wish to create.")
        name = input()
inappropriate = "<>#!@$%^&*()_- {}"
if not any(map(lambda char: char in inappropriate, name)):
    # The name is not alright.

the map function is mapping the lambda function with any character in the name.  This will produce a list of the results of the lambda function. And any() returns True if there is not any value in the list which could be considered False - None, 0, False, empty value.
@wavic
using if not any is wrong and would yield the opposite result
name = 'test'
inappropriate = "<>#!@$%^&*()_- {}"
if not any(map(lambda char: char in inappropriate, name)):
    print('invalid')
Output:
invalid
and there is no need to complicate it with using lambda, keep it simple

inappropriate = "<>#!@$%^&*()_- {}"
if any(char in inappropriate for char in name):
    # The name is not alright.