2

I am currently writing some python code that asks for a users name. I need the program to validate whether the user's input is a string or not. If it is a string, The loop will break and the programme will continue. If the input is not a string (like a float, integer etc), It will loop around and ask the user to input a valid string. I understand that you can use the following code when you are checking for an integer;

while True:
try:
    number = int(input("Plese enter a number: "))
    break
except ValueError:
    print("Please enter a valid integer")

I was thinking that I could use something like this to check for a string;

while True:
try:
    word = str(input("Plese enter a string: "))
    break
except ValueError:
    print("Please enter a valid string")

But as far as I understand, the str() just converts the user's input to a string, regardless of the data that was entered.

Please help!

thanks

Tech Dynasty
  • 163
  • 1
  • 4
  • 11
  • 1
    I don't quite get what you are trying to do. What's a valid string to you? – Ozgur Vatansever May 16 '17 at 21:05
  • 1
    Possible duplicate of [How to check if type of a variable is string?](http://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string) – Ozgur Vatansever May 16 '17 at 21:07
  • So, I want the programme to check whether the user has typed in a string. If so, it will break the loop as shown in the code. If the user has entered another type of data (integer, float etc), It will tell them to try again. – Tech Dynasty May 16 '17 at 21:07
  • 4
    It's *always* a string. Even if they type `487`, you'll get a string. – user2357112 May 16 '17 at 21:09
  • Do you mean you want to know if the user entered only alphabetic characters (no numeric or special characters)? – MrMas May 16 '17 at 21:14
  • @MrMas . Yes. I only want alphabetic characters (: – Tech Dynasty May 16 '17 at 21:16
  • This post may be of some help: http://stackoverflow.com/questions/16060899/alphabet-range-python of course it doesn't deal with anything but the English alphabet. – MrMas May 16 '17 at 21:18
  • This may have helped me @MrMas , I'm going to try something a bit different, will let you know if it works (: – Tech Dynasty May 16 '17 at 21:20
  • The problem has been solved by @OzgurVatansever , But thanks for the help (: – Tech Dynasty May 16 '17 at 21:23

1 Answers1

1

Based on the comments, it looks like you want to check if the input consists of alphabetic characters only. You can use .isalpha() method:

while True:
    word = input("Please enter a string: ")
    if word.isalpha():
        # Do something with valid input.
        break
    else:
        print("Please enter a valid string")    
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119