当前位置: 移动技术网 > IT编程>脚本编程>Python > Python2 中 input() 和 raw_input() 的区别

Python2 中 input() 和 raw_input() 的区别

2018年12月18日  | 移动技术网IT编程  | 我要评论

爆米花龙将,将夜sodu,对话马云

在 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 "<stdin>", line 1, in <module>
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.

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网