繁体   English   中英

如何在python上限制用户输入长度?

[英]How can I limit user input length on python?

amt = float(input("Please enter the amount to make change for: $"))

我希望用户以美元为单位输入金额,因此允许 5 个字符 (00.00) 有没有办法限制它,这样他们就不会输入超过 5 个字符?

我不想要这样的东西,它允许您输入超过 5 个但会循环。

while True:
amt = input("Please enter the amount to make change for: $")
if len(amt) <= 5:
        print("$" + amt)
        break

我想完全限制输入超过 5 个字符

使用诅咒

还有其他方法,但我认为这是一个简单的方法。

阅读 Curses 模块

您可以使用getkey()getstr () 但是使用 getstr() 更简单,如果用户愿意,它可以让用户选择输入少于 5 个字符,但不超过 5 个。我认为这就是您的要求。

 import curses
 stdscr = curses.initscr()
 amt = stdscr.getstr(1,0, 5) # third arg here is the max length of allowed input

但是如果你想强制 5 个字符,不多也不少,你可能想使用 getkey() 并将其放入 for 循环中,在这个示例程序中,在继续之前,将等待用户输入 5 个字符,甚至不需要按回车钥匙。

amt = ''
stdscr = curses.initscr() 
for i in range(5): 
     amt += stdscr.getkey() # getkey() accept only one char, so we put it in a for loop

笔记:

您需要调用 endwin() 函数将终端恢复到其原始操作模式。

调试 curses 应用程序时的一个常见问题是,当应用程序死掉而不将终端恢复到以前的状态时,终端就会变得一团糟。 在 Python 中,当您的代码有问题并引发未捕获的异常时,通常会发生这种情况。 例如,当您键入时,键不再显示在屏幕上,这使得使用 shell 变得困难。

放在一起:

继续第一个例子,在你的程序中实现 getstr() 方法可能是这样的:

import curses 

def input_amount(message): 
    try: 
        stdscr = curses.initscr() 
        stdscr.clear() 
        stdscr.addstr(message) 
        amt = stdscr.getstr(1,0, 5) # or use getkey() as showed above.
    except: 
        raise 
    finally: 
        curses.endwin() # to restore the terminal to its original operating mode.
    return amt


amount = input_amount('Please enter the amount to make change for: $') 
print("$" + amount.decode())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM