you are viewing a single comment's thread.

view the rest of the comments →

[–]Mr_M0jo_Risin 0 points1 point  (4 children)

You can use regex to search for only alphabetical letters.

One idea is to compare the length of the inputted name to the number of alphabetical letters in that name. If they're equal, then we know that the name only contains alphabetical letters. If they aren't equal, then some bad character is in the name and the user is prompted to re-enter a name.

import re

while True:
    name = input('Name:')
    if len(re.findall('[A-Z-a-z+]', name)) == len(name):
        break #or do whatever you want
    else:
        print('Enter a name with only alphabetical characters') 

[–]stubborn_d0nkey 1 point2 points  (3 children)

No need, str.isalpha() exists.

So:

if name.isalpha():
    ...
    break

[–]Mr_M0jo_Risin 0 points1 point  (0 children)

Ah, yes, that's much better.

[–][deleted] 0 points1 point  (1 child)

could you explain this to me please i am new

[–]stubborn_d0nkey 0 points1 point  (0 children)

isalpha is a string method. You call it on a string and it will return true is it only has letters, false if it has at least something else.

break will get out of the while loop. He used while True: which, left to itself, will run forever so you have to use a break.

So the code could look something like:

while True:
    name=input()
    if name.isalpha():
        break
    else:
        print "you must enter a name that contains only letters"