限制 raw_input 長度

2024-04-24 13:38:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个解决方案来限制用户可以在原始输入中键入的字符数。我在同一行有两个原始输入,如下所示:

Name: (user input)                           Date of Birth: (user input)

如果用户输入的名称大于X个字符,它将从出生日期开始写入,如下所示:

^{pr2}$

我找到的最接近的东西是:Limiting Python input strings to certain characters and lengths,但这对我来说不起作用。我不希望它显示警告;我希望它停止接受更多字符和/或转到下一个输入。在

我使用的是breeded,这是一个库,它使用curses将第二个输入与第一个输入放在同一行中。在

有什么想法吗?在


Tags: of用户name名称inputdate键入解决方案
2条回答

这是一个我刚刚提出的一个整洁的东西,可能有助于某人查看这条没有使用诅咒的帖子。在输入期间有效地约束用户输入的字符串长度。在

import readchar
import sys

string = ""

while len(string) < 20:
    c = readchar.readchar()
    sys.stdout.write(c)
    string += c

print '\n' + string

函数getstr()cursesraw_input替代方法,它使用字符约束:

s = stdscr.getstr(0,0, 15) #Input is limited to 15 characters, once the limit is hit, it stops accepting more

相关问题 更多 >