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

試著忘記壹切 提交于 2019-12-12 04:04:14

问题


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 `


回答1:


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)



回答2:


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




回答3:


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!')


来源:https://stackoverflow.com/questions/45650945/how-to-check-if-the-user-input-is-a-string-in-python-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!