ifs*_*ife 49 python input raw-input
我正在使用python2.7 raw_input
来从stdin读取.
我想让用户更改给定的默认字符串.
码:
i = raw_input("Please enter name:")
Run Code Online (Sandbox Code Playgroud)
安慰:
Please enter name: Jack
Run Code Online (Sandbox Code Playgroud)
应该向用户显示Jack
但可以将其更改(退格)为其他内容.
该Please enter name:
参数将是提示,raw_input
并且该部分不应该由用户改变.
cod*_*eak 80
你可以这样做:
i = raw_input("Please enter name[Jack]:") or "Jack"
Run Code Online (Sandbox Code Playgroud)
这样,如果用户只是按下返回而不输入任何内容,"i"将被分配为"Jack".
Eri*_*ski 16
Python2.7获取raw_input并设置默认值:
把它放在一个名为a.py的文件中:
import readline
def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return raw_input(prompt)
finally:
readline.set_startup_hook()
default_value = "an insecticide"
stuff = rlinput("Caffeine is: ", default_value)
print("final answer: " + stuff)
Run Code Online (Sandbox Code Playgroud)
运行该程序,它停止并向用户显示以下内容:
el@defiant ~ $ python2.7 a.py
Caffeine is: an insecticide
Run Code Online (Sandbox Code Playgroud)
光标在最后,用户按下退格键直到'杀虫剂'消失,键入其他内容,然后按回车键:
el@defiant ~ $ python2.7 a.py
Caffeine is: water soluable
Run Code Online (Sandbox Code Playgroud)
程序完成这样,最终答案得到用户键入的内容:
el@defiant ~ $ python2.7 a.py
Caffeine is: water soluable
final answer: water soluable
Run Code Online (Sandbox Code Playgroud)
相当于上面,但在Python3中工作:
import readline
def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt)
finally:
readline.set_startup_hook()
default_value = "an insecticide"
stuff = rlinput("Caffeine is: ", default_value)
print("final answer: " + stuff)
Run Code Online (Sandbox Code Playgroud)
有关这里发生了什么的更多信息:
在dheerosaur的回答中如果用户按Enter键来实际选择默认值,它将不会被保存,因为python将其视为''字符串,因此延伸了一下dheerosaur.
default = "Jack"
user_input = raw_input("Please enter name: %s"%default + chr(8)*4)
if not user_input:
user_input = default
Run Code Online (Sandbox Code Playgroud)
Fyi .. ASCII value
退格是08
在具有 的平台上readline
,您可以使用此处描述的方法:https ://stackoverflow.com/a/2533142/1090657
在 Windows 上,您可以使用 msvcrt 模块:
from msvcrt import getch, putch
def putstr(str):
for c in str:
putch(c)
def input(prompt, default=None):
putstr(prompt)
if default is None:
data = []
else:
data = list(default)
putstr(data)
while True:
c = getch()
if c in '\r\n':
break
elif c == '\003': # Ctrl-C
putstr('\r\n')
raise KeyboardInterrupt
elif c == '\b': # Backspace
if data:
putstr('\b \b') # Backspace and wipe the character cell
data.pop()
elif c in '\0\xe0': # Special keys
getch()
else:
putch(c)
data.append(c)
putstr('\r\n')
return ''.join(data)
Run Code Online (Sandbox Code Playgroud)
请注意,箭头键不适用于 Windows 版本,使用时不会发生任何事情。
我仅添加此内容是因为您应该编写一个简单的函数以进行重用。这是我写的:
def default_input( message, defaultVal ):
if defaultVal:
return raw_input( "%s [%s]:" % (message,defaultVal) ) or defaultVal
else:
return raw_input( "%s " % (message) )
Run Code Online (Sandbox Code Playgroud)
dhe*_*aur -4
尝试这个:raw_input("Please enter name: Jack" + chr(8)*4)
backspace
的ASCII 值为08
。