检查用户输入是否是Python中的str

检查用户输入是否是Python中的str,python,Python,我检查了关于堆栈溢出的各种问题,但每个逻辑都缺少一件事。让我演示如何使用Python: while True: user_input = raw_input() if type(user_input) == str: print 'ERROR' else: print 'BINGO' 此外,我们不能使用input()代替raw_input(),因为它会给出错误:Traceback(最近一次调用last): 然后,它给出了一个错误: Tra

我检查了关于堆栈溢出的各种问题,但每个逻辑都缺少一件事。让我演示如何使用Python:

while True:
    user_input = raw_input()
    if type(user_input) == str:
        print 'ERROR'
    else:
        print 'BINGO'
此外,我们不能使用input()代替raw_input(),因为它会给出错误:Traceback(最近一次调用last):

然后,它给出了一个错误:

Traceback (most recent call last):
  File ".\test.py", line 3, in <module>
    user_input = int(raw_input())
ValueError: invalid literal for int() with base 10: 'asdf'
回溯(最近一次呼叫最后一次):
文件“\test.py”,第3行,在
用户输入=int(原始输入()
ValueError:基数为10的int()的文本无效:“asdf”

我用try和except尝试了这一点,但检查整数(而不是字符串)会很好。

您完全是反向操作的-
原始输入不
“将用户输入转换为字符串”-用户输入一开始就是字符串!是
input
将其转换为其他内容

如果您想使用
原始输入
,您可以假设您将获得一个字符串,您需要自己将其转换为int。如您所见,如果字符串不表示整数,则此操作将失败,但您可以轻松捕获该错误:

while True:
    user_input = raw_input()
    try:
        user_input_as_integer = int(user_input)
        print 'BINGO'
    except ValueError:
        print 'ERROR'

无论您是否输入整数,
raw\u input
始终存储字符串。

Hmmm,您希望
raw\u input
如何确切地知道用户下一次击键将是整数?相反,您如何期望
int
函数将
asdf
转换为整数?您得到了两次写入中的一次。通过这个OK,它说,
raw\u input
将输入转换为字符串-但是这种转换不是以你的问题暗示的方式进行的。例如,当用户输入
10
时,
raw_input
不会将其从int
10
转换为字符串
'10'
——它从一开始就不是int。文档的意思是
raw\u input
将字节数组或缓冲区之类的输入转换为Python字符串对象。
Traceback (most recent call last):
  File ".\test.py", line 3, in <module>
    user_input = int(raw_input())
ValueError: invalid literal for int() with base 10: 'asdf'
while True:
    user_input = raw_input()
    try:
        user_input_as_integer = int(user_input)
        print 'BINGO'
    except ValueError:
        print 'ERROR'
# first store the value to a variable
user_input = raw_input('>')
try:
    if int(user_input):
        print "User entered %d is integer" % int(user_input)
except ValueError: 
    # check whether the user entered string or not
    print "User entered %s is a string" % user_input