-2

My first question on here...

I want to know how to check if the user input is a string. If it is not a message should appear. Otherwise the answer should be accepted. Here is what I have (I am looking for the simplest fix please):

try:
    name=str(raw_input("What is your name? "))
except:
    print("Your name must consist of letters only")
else:
    print("Thank you for entering your name.")
S McMahon
  • 1
  • 1
  • 2
  • Possible duplicate of [How can I check if a string contains ANY letters from the alphabet?](http://stackoverflow.com/questions/9072844/how-can-i-check-if-a-string-contains-any-letters-from-the-alphabet) – Richard Erickson Dec 04 '15 at 13:39
  • Here is something interesting to read if you want to validate names: http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ – Andrea Dusza Dec 04 '15 at 13:40
  • `raw_input` always returns a string, so you don't have to do anything ;-) did you mean to ask "how to check if user input contains only alphabetical characters"? – Kevin Dec 04 '15 at 13:44

2 Answers2

3

str.isalpha() checks if all characters in the string are alphabetic and there is at least one character. So

name=str(raw_input("What is your name? "))
if not name.isalpha():
    print("Your name must consist of letters only")
else:
    print("Thank you for entering your name.")

However this will not work if name is "Homer Simpson" (with a space) which is valid input for name.

And don't you forget this!!!

Psytho
  • 3,313
  • 2
  • 19
  • 27
1

What about an assertion with the check for non ascii letters in the string , similar to here,

import string
try:
    name = raw_input("What is your name? ")
    assert  any([char not in string.ascii_letters for char in name]) is False
except AssertionError:
    print("Your name must consist of letters only")
else:
    print("Thank you for entering your name.")
Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • Ok, now how do you check for characters that aren't letters or digits, such as "~"? – Kevin Dec 04 '15 at 13:45
  • What if `name` contains `,` or `&`? – Psytho Dec 04 '15 at 13:45
  • Good point, I assumed string would want anything but numbers. I've changed to check for all ascii letters. If the name had an accent, etc this may need to be expanded (e.g. using `string.printable` instead of `string.ascii_letters`). – Ed Smith Dec 04 '15 at 15:06