Allow Only Alpha Characters in Python?

后端 未结 5 1539
逝去的感伤
逝去的感伤 2020-12-12 06:24

I am writing a program, part of it requires the input of a name. The name can only be alpha and spaces (eg. John Smith) it cannot be John Smith1 If an invalid character IS

相关标签:
5条回答
  • 2020-12-12 06:42

    Try the isalpha() method of strings.

    Since the person will enter names with spaces, you have two options:

    1. Split the input by the space (use split())
    2. Take advantage of string.letters

    For example:

       >>> import string
       >>> string.letters
       'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    

    Combine that with a ' ' to get your list of allowed characters. Since this is homework, the rest is up to you.

    0 讨论(0)
  • 2020-12-12 06:43

    Use Regular Expressions, something like [A-Za-z ]+

    It would translate into something like this, if I use Tim's expression:

    match = re.match(r'^[A-Za-z ]*$', name )
    if match :
        print("Correct name");
    else:
        print("Invalid chars");
    
    0 讨论(0)
  • 2020-12-12 06:46

    To Check the string for alpha I generally use this one. Hope this can help you.

    import re
    def is_alpha_space(name):
        name_nospace = ''.join((name.split()))
        if re.search(r"\W", name_nospace) or len(name_nospace) < 1:
            return False
        return True
    name = "Mark Zumkoff"
    print(is_alpha_space(name))  # True
    name = "Mark Zumkoff@"
    print(is_alpha_space(name))  # False
    name = "    "
    print(is_alpha_space(name))  # False
    
    0 讨论(0)
  • 2020-12-12 06:56

    You might want to look into regular expressions:

    ^[A-Za-z ]*$
    

    is a regex that only matches strings if they consist entirely of ASCII letters and spaces.

    To also allow letters of your current locale:

    ^[^\W\d_]*$
    

    which is basically the set of alphanumeric characters including accented characters (in the current locale) minus digits and underscore.

    0 讨论(0)
  • 2020-12-12 07:03

    You can use the replace method of strings to get rid of white-spaces and then use the isalpha() method.

    An example:

    >>> def get_name():
    ...     name = raw_input('name: ')    # use a simple "input" in python3
    ...     if not name.replace(' ', '').isalpha():
    ...             print('Bad name!!!')
    ...     else:
    ...             print('Good name!')
    ... 
    >>> get_name()
    name: My name
    Good name!
    >>> get_name()
    name: Bad Nam3
    Bad name!!!
    >>> get_name()
    name: Jon Skeet
    Good name!
    

    Note that this works also with non ascii-letters in python3:

    #python3
    >>> get_name()
    name: Accented è
    Good name!
    >>> get_name()
    name: Bad Nam3
    Bad name!!!
    

    Regular expressions are too complicated for this simple task. Also because using [A-Za-z ]+ or similar wont match names with non ASCII letters. And using \w includes digits.

    If you don't want to match non-ASCII letters(such as 'è'), then you can try something like this:

    >>> def get_name():
    ...     name = raw_input('name: ')   #input in python3
    ...     try:
    ...             name.encode('ascii')
    ...     except UnicodeDecodeError:
    ...             print('Bad name!!!')
    ...             return
    ...     if not name.replace(' ', '').isalpha():
    ...             print('Bad name!!!')
    ...     else:
    ...             print('Good name!')
    ... 
    >>> get_name()
    name: Accented è
    Bad name!!!
    >>> get_name()
    name: The nam3
    Bad name!!!
    >>> get_name()
    name: Guido Van Rossum
    Good name!
    

    Finally, an other way to check is this one:

    >>> import string
    >>> def good_name(name):
    ...     return not set(name).difference(string.letters + ' ')
    ... 
    >>> good_name('Guivo Van Rossum')
    True
    >>> good_name('Bad Nam3')
    False
    

    And you can use it in this way:

    name = raw_input('name: ')   #input in python3
    if good_name(name):
       #stuff for valid names
    else:
       #stuff for invalid names
    
    0 讨论(0)
提交回复
热议问题