.isalpha () with spaces does not work in Python 3x

1
equipos = ["Barcelona", "Real Madrid", "Manchester United", "Ajax"]

print (equipos[0])
print (equipos[1])
print (equipos[2])
print (equipos[3])

while True:
    equipo = input("\n¿Con que equipo te gustaria jugar? Escribelo aqui: ")

    if equipo.isalpha() :
        if equipo == "Barcelona":
            print ("Buena eleccion!")
            break
        if equipo == "Real Madrid":
            print ("Buena eleccion!")
            break
        if equipo == "Manchester United":
            print ("Buena eleccion!")
            break
        if equipo == "Ajax":
            print ("Buena eleccion!")
            break
        else:
            print("Elije un equipo de la lista, porfavor.")

    else:
        print ("Por favor, utiliza solo letras.")

By using .isalpha() I noticed that if there is a space in the word, like Real Madrid, it does not work. With Ajax and Barcelona it works perfectly. How can this be solved?

    
asked by user28359 21.02.2017 в 11:39
source

2 answers

2

.isalpha() only returns True if all the characters in the string they are alphabetic and there is at least one character, otherwise returns False .

If the check also has to accept blanks, you can use something like this:

if all(x.isalpha() or x.isspace() for x in equipo):

This expression will be True for strings that contain spaces and alphabetic characters. However, if you need to also accept numeric characters (for example Shalke 04 ), you must modify the expression to allow them:

if all(x.isalnum() or x.isspace() for x in equipo):
    
answered by 21.02.2017 / 11:58
source
1

isAlpha() returns true if all the characters are alphabetic and there is at least 1 character. Returns false because space is not an alphabetic character.

The simplest would be to replace the spaces with empty and then use isalpha() :

equipo.replace(" ", "").isalpha()

Another way to detect that you have only letters (and spaces) you can use Regex :

import re
while True:
    equipo = input("\n¿Con que equipo te gustaria jugar? Escribelo aqui: ")

    pattern = re.compile("^[A-Z ]+$")

    if pattern.match(equipo.upper()):
        if equipo == "Barcelona":
            print ("Buena eleccion!")
            break
        if equipo == "Real Madrid":
    . . . 

The regular expression ^[A-Z ]+ supports letters and spaces. You can add Numbers by:

  

^[A-Z0-9 ]+$

Note: In the checks that you make of "equipo == "Barcelona":" you run the risk that put "barcelona" and no longer work. For that, put both a upper() or lower() such that:

equipo.lower() == "Barcelona".lower():
    
answered by 21.02.2017 в 12:02