开发者

Is there a way to accept '%' as part of input that works both in python 2.6 & 3.0?

开发者 https://www.devze.com 2023-01-04 05:48 出处:网络
In 2.6, if I needed to accept input that allowed a percent sign (such as \"foo % bar\"), I used raw_input() which worked as expected.

In 2.6, if I needed to accept input that allowed a percent sign (such as "foo % bar"), I used raw_input() which worked as expected.

In 3.0, input() accomplishes that same (with raw_input() having left the building).

As an exercise, I'm hoping that I can have a backward-compatible version that will work with both 2.6 and 3.0.

When I use input() in 2.6 and enter "foo % bar", the following error is returned:

  File "<string>", line 1, in <module>
NameError: name "foo" is not defined

...which is expected.

Anyway to to accomplish acceptance of input containing a percent sign that work开发者_Go百科s in both 2.6 and 3.0?

Thx.


You can use sys.version_info to detect which version of Python is running.

import sys
if sys.version_info[0] == 2:
    input = raw_input
# Now you can use
input()

Alternatively, if you don't want to override Python 2.X's builtin input function, you can write

import sys
if sys.version_info[0] == 2:
    my_input = raw_input
else:
    my_input = input
# Now you can use
my_input()

Although, even in my first code sample, the original builtin input is always available as __builtins__.input.


Although not an elegant (and rather ugly) solution, I would just do something like this:

try:
    input = raw_input
except:
    pass
0

精彩评论

暂无评论...
验证码 换一张
取 消