Restricting The User Input To Alphabets
Solution 1:
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha()
:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha()
in your if-statement instead of x==r
.
Solution 2:
I don't understand what you're trying to do with
x = r
ifx== r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print"WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
whilenot r.match(x):
print"Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if5<=len(x)<=10:
print"Hi,", x, "!"eliflen(x)>10:
print"Mmm,Your name is too long!"eliflen(x)<5:
print"Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
whilenot x.isalpha():
Solution 3:
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
ifnot namefield.isalpha():
print"Please use only alpha charactors"elifnot4<=len(namefield)<=10:
print"Name must be more than 4 characters and less than 10"else:
print"hello" + namefield
isalpha
will check to see if the whole string is only alpha characters. If it is, it will return True.
Post a Comment for "Restricting The User Input To Alphabets"