接受输入作为单词而不是整数

时间:2015-03-18 21:02:53

标签: python python-3.x input words

如何在Python中进行单词输入 我希望能够让计算机向用户提出问题,如

test = int(input('This only takes a number as an answer'))

我希望能够让'测试'不是数字,而不是单词或字母。

5 个答案:

答案 0 :(得分:3)

只需删除int来电! 是使语句只接受整数的原因。

即,使用:

test = input('This takes any string as an answer')

答案 1 :(得分:2)

删除投射到int

的类型
test = input('This only takes a word as an answer :')

演示

>>> test = input('This only takes a word as an answer :')
This only takes a word as an answer :word
>>> test
'word'

注意 - 来自docs

  

然后函数从输入读取一行,将其转换为字符串(剥离尾随换行符),然后返回

因此input会自动将其转换为str,并且不需要任何明确的演员。

答案 2 :(得分:0)

这应该有效:

test = str(input('This only takes a string as an answer:  '))

BUT

因为默认情况下Python使用String,实际上你不需要像intstr

这样的任何投射

另外,如果您使用的是3.x之前的版本,那么它将是raw_input而不是input。由于您的解决方案似乎已接受input,因此假设您的Python没问题我可以安全。     test = input('这只是一个字符串作为答案')

答案 3 :(得分:0)

 test = input("This only takes a number as an answer")
 test = raw_input("This only takes a number as an answer")

任何一个都应该工作

答案 4 :(得分:0)

如果您使用的是python 2.7,只需使用raw_input函数。

test = raw_input('This only takes a string as an answer:  ')

即:

>>> test = raw_input('This only takes a string as an answer:  ')
This only takes a string as an answer:  2.5
>>> type (test)
<type 'str'>

如果您使用输入,则只能有一个数字: 正确的输入:

>>> test = input('This only takes a number as an answer:  ')
This only takes a string as an answer:  2.5
>>> type (test)
<type 'float'>

错误的输入:

>>> test = input('This only takes a number as an answer:  ')
This only takes a number as an answer:  word
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'word' is not defined