python命令行输入函数回退_Python2 中 input() 和 raw_input() 的区别

在 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.

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值