Python - User input data type
我在Python 3.x中编写了以下代码来验证用户的输入:
1 2 3 4 5 | while True: try: answer = int(input("Enter an integer:")) except ValueError: print("That's not a whole number. Try again.") |
我知道输入'hi'或'hi46'将是字符串(并且会导致ValueError)。
什么数据类型输入''(无)是什么? 输入']%$'(符号)怎么样?
假设您正在使用python 3.X,用户输入的所有内容都将是一个字符串。 甚至数字看上去像"23"或"0"。
示范:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | >>> while True: ... x = input("Enter something:") ... print("You entered {}".format(x)) ... print("That object's type is: {}".format(type(x))) ... Enter something: hi You entered hi That object's type is: <class 'str'> Enter something: hi46 You entered hi46 That object's type is: <class 'str'> Enter something: You entered That object's type is: <class 'str'> Enter something: ]%$ You entered ]%$ That object's type is: <class 'str'> Enter something: 23 You entered 23 That object's type is: <class 'str'> Enter something: 42 You entered 42 That object's type is: <class 'str'> Enter something: 0 You entered 0 That object's type is: <class 'str'> |
您可以在不依赖于使用isdigit()的异常的情况下执行此操作:
1 2 3 4 5 | answer = input("Enter an integer:") while not answer.isdigit(): print("That's not a whole number. Try again.") answer = input("Enter an integer:") answer = int(answer) |
isdigit()测试输入字符串是否完全由可以用int()转换的数字组成。
字符串,你