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

9
  • 1
    I don't quite get what you are trying to do. What's a valid string to you? Commented May 16, 2017 at 21:05
  • 1
    Possible duplicate of How to check if type of a variable is string? Commented May 16, 2017 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. Commented May 16, 2017 at 21:07
  • 4
    It's always a string. Even if they type 487, you'll get a string. Commented May 16, 2017 at 21:09
  • Do you mean you want to know if the user entered only alphabetic characters (no numeric or special characters)? Commented May 16, 2017 at 21:14

1 Answer 1

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")    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.