【发布时间】:2014-11-15 22:24:29
【问题描述】:
我是Python 的新手。在 Python 中,input() 和 raw_input() 逐行读取,而在 C/C++ 中,读取输入的默认分隔符是空格。
我知道我可以使用split() 来获取列表。没有空格作为默认输入分隔符有什么意义吗?
【问题讨论】:
我是Python 的新手。在 Python 中,input() 和 raw_input() 逐行读取,而在 C/C++ 中,读取输入的默认分隔符是空格。
我知道我可以使用split() 来获取列表。没有空格作为默认输入分隔符有什么意义吗?
【问题讨论】:
在 Python 2 中,input() 接受来自用户的一行代码,执行它并返回结果——因此逐行而不是逐字阅读的意义在于它使该过程更加容易。 raw_input 是 input 的双胞胎,除了它没有尝试评估输入的内容,它只是将其作为 str 返回。
运行用户输入也很危险,这就是为什么它在 Python 3 中被删除,而raw_input 取代了input。
Python 2:
--> test_var = input('enter a number: ')
# user enters "71 + 9" (without quotes), Python tries to run the text entered
--> test_var
# 80
--> type(test_var)
# <type 'int'>
--> test_var = raw_input('enter another number: ')
# user enters "99 - 9", Python simply gives back the string '99 - 9'
--> test_var
# '99 - 9'
--> type(test_var)
# <type 'str'>
--> test_var = input('enter something')
# user enters "howdy" (without the quotes)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'howdy' is not defined
【讨论】:
input() 将根据用户输入的内容调用 eval()。因此,如果您输入 22+5,input() 将返回 27。另一方面,raw_input() for 22+5 将产生 "22+5"。
在 Python 中,输入默认类型为 string,在 string 对象的值中,允许使用空格(例如 s = "Bob Fred")。 split(delim) 用于通过指定的分隔符拆分字符串对象(同样,如果您将 delim 参数留空,则默认分隔符是空格)。
我认为这是一个默认选择(设计决策),因为您很快就会意识到将字符串转换为整数、浮点数等类型的数据类型非常简单。
【讨论】:
raw_input (python 2) / input (python 3) 的重点是返回字符串。我们不会改变这一点。