在 python2 中如要想要获得用户从命令行的输入,可以使用 input() 和 raw_input() 两个函数,那么这两者有什么区别呢?
我们先借助 help 函数来看下两者的文档注释:
>>> help(raw_input)
help on built-in function raw_input in module __builtin__:
raw_input(...)
raw_input([prompt]) -> string
read a string from standard input. the trailing newline is stripped.
if the user hits eof (unix: ctl-d, windows: ctl-z+return), raise eoferror.
on unix, gnu readline is used if enabled. the prompt string, if given,
is printed without a trailing newline before reading.
>>> help(input)
help on built-in function input in module __builtin__:
input(...)
input([prompt]) -> value
equivalent to eval(raw_input(prompt)).
可以看出,raw_input() 返回的始终是一个“原始”(raw)字符串,并且去掉了行末的换行符。
值得注意的是,文档还提到“on unix, gnu readline is used if enabled. ”,
这是说,如果 *nix 系统中安装了 gnu readline 库,并且在 python 中启用了(import readline),那么 raw_input() 底层就会调用这个库。
如果不启用,raw_input() 也能用,只不过会读取你键盘输入的所有字符,包括不可见字符,比如回退键……这样就很不方便了是不是。
而 input() 其实是在 raw_input() 返回的结果上再 调用了 eval() 函数,把原始字符串计算成 python 可以识别的对象。
在 pyhon3 中,已经没有 raw_input() 函数了,而剩下 input() 函数与 python2 中的 raw_input() 行为一致:
>>> help(raw_input)
traceback (most recent call last):
file "", line 1, in
nameerror: name 'raw_input' is not defined
>>> help(input)
help on built-in function input in module builtins:
input(prompt=none, /)
read a string from standard input. the trailing newline is stripped.
the prompt string, if given, is printed to standard output without a
trailing newline before reading input.
if the user hits eof (*nix: ctrl-d, windows: ctrl-z+return), raise eoferror.
on *nix systems, readline is used if available.
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!