gpt4 book ai didi

python - raw_input 占位符?

转载 作者:太空宇宙 更新时间:2023-11-03 19:11:38 28 4
gpt4 key购买 nike

Possible Duplicate:
Show default value for editing on Python input possible?

我想要一个raw_input要求确认某事。有没有办法在用户输入任何内容之前就已经“输入”了文本?例如:

>>> x = raw_input('1 = 2. Correct or incorrect? ', 'correct')
1 = 2. Correct or incorrect? correct

这可以与 <imput type="text" value="correct"> 进行比较在 HTML 中。文本将自动为用户输入,但如果他们愿意,他们可以添加或删除全部/部分文本。这可以吗?

最佳答案

<小时/>

示例 1:

def make_question(question, *answers):
print question
print
for i, answer in enumerate(answers, 1):
print i, '-', answer

print
return raw_input('Your answer is: ')

测试代码:

answer = make_question('Test to correctness:', 'correct', 'not correct')
print answer

输出:

Test to correctness:

1 - correct
2 - not correct

Your answer is: correct
correct
<小时/>

示例 2:

input = raw_input('Are you sure?: [Y]') # [Y] - YES by default
if input.lower() in ['n', 'no']:
exit() # or return...
<小时/>

示例 3(更复杂):

import termios, fcntl, sys, os

def prompt_user(message, *args):
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

sys.stdout.write(message.strip())
sys.stdout.write(' [%s]: ' % '/'.join(args))

choice = 'N'
lower_args = [arg.lower() for arg in args]
try:
while True:
try:
c = sys.stdin.read(1)
if c.lower() in lower_args:
sys.stdout.write('\b')
sys.stdout.write(c)
choice = c

if c == '\n':
sys.stdout.write('\n')
break

except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

return choice

用法:

print prompt_user('Are you sure?', 'Y', 'N', 'A', 'Q')

在 Unix/Linux 控制台(不是来自 IDE)中工作

关于python - raw_input 占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772766/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com