Garde Des Ombres
Garde Des Ombres

Reputation: 191

how to check if the user input is a string in python 3

I wrote the code below:

try:
    nums=input("Write a name:")
    print (nums)
except ValueError:
    print ("You didn't type a name")

The problem is that even the user enter a number the program prints it `

Upvotes: 1

Views: 3469

Answers (3)

S.Babovic
S.Babovic

Reputation: 335

You can use the function yourstring.isalpha() it will return true if all characters in the string are from the alphabet. So for your example:

nums = input("write a name:")
if(not nums.isalpha()):
    print("you did not write a name!")
    return
print(nums)

Upvotes: 1

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

You can use regex like this example:

import re

while True:
    try:
        name = input('Enter your name: ')
        validate = re.findall(r'^[a-zA-Z]+$', name)
        if not validate:
            raise ValueError
        else:
            print('You have entered:', validate[0])
            break
    except ValueError:
        print('Enter a valid name!')

Upvotes: 0

Thomite
Thomite

Reputation: 741

You can use the builtin Python function type() to determine the type of a variable.

Upvotes: 0

Related Questions