Admit letters and spaces in Python

2

I have a program that registers first and last name and I have a filter so that characters that are not letters are not allowed, but the space, since it is not a letter, does not support it and I can not put the last name.

Does anyone know how I can admit spaces?

I have seen the S.isspace() statement, but I do not see any utility since it only returns True if the whole string has spaces.

Code:

nmyap1 = (input("MESA 1: Ingresa nombre y apellido de 1era persona: "))
while (len(nmyap1)>20) or (not (nmyap1.isalpha())):
    nmyap1 = (input("Demasiados car. (max 20) o car. invalido, ingrese otra vez: "))
    
asked by Power 03.12.2016 в 06:05
source

2 answers

3

str.isspace() returns True for all types of blank separators, such as spaces or tabs. If you only want to allow spaces you can use a type check:

while (len(nmyap1)>20) or (not (all(c.isalpha() or c==' ' for c in nmyap1))):
    ...
    
answered by 03.12.2016 в 06:38
1

Alternatively you can use a regular expression to validate the characters and length using re.fullmatch () .

Code:

import re

nmyap1 = input("MESA 1: Ingresa nombre y apellido de 1era persona: ")
while (not re.fullmatch(r"[A-Za-z ]{1,20}", nmyap1)):
    nmyap1 = input("\nDemasiados car. (max 20) o car. invalido, ingrese otra vez: ")

Demo: link


Description:

re.fullmatch() uses a regular expression to test if it matches an entire text . The function returns a Match object if it matches or None if it does not match (which evaluates to False ).

The regular expression [A-Za-z ]{1,20} matches only between 1 and 20 letters or spaces. By denying the result with not , the loop is executed when it does not match.

To allow characters in Spanish, it can be replaced by the regular expression:

[A-Za-zÁÉÍÓÚÜÑáéíóúüñ ]{1,20}
    
answered by 03.12.2016 в 10:09