如何为raw_input设置默认字符串?

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

  • 这不适合这个问题."杰克"不可编辑. (6认同)
  • @chubbsondubs问题不是关于_common Unix pattern_。 (2认同)

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)

有关这里发生了什么的更多信息:

/sf/answers/177319971/

  • 这应该也适用于 Windows 还是只适用于 Linux? (2认同)

Anu*_*nuj 7

在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

  • 这是一个巧妙的伎俩,谢谢.仍然不是我想要的,因为用户无法真正更改给定的默认字符串或使用箭头键进行导航.当然,人们可以解决这个问题,但是这个小功能有点超出了范围. (2认同)

qua*_*tum 5

在具有 的平台上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 版本,使用时不会发生任何事情。


chu*_*ubs 5

我仅添加此内容是因为您应该编写一个简单的函数以进行重用。这是我写的:

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

  • `Jack` 只是打印出来,但没有设置为默认值。 (2认同)