首页 > 解决方案 > 如何在 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 个字符

标签: python

解决方案


使用诅咒

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

阅读诅咒模块

您可以使用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())

推荐阅读