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

Che*_*rry 9 python

amt = float(input("Please enter the amount to make change for: $"))
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Sam*_*ouk 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
Run Code Online (Sandbox Code Playgroud)

但是如果您想强制不超过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
Run Code Online (Sandbox Code Playgroud)

注意:

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

调试curses应用程序时,一个常见的问题是在应用程序死机时弄乱了终端,而又没有将终端恢复到以前的状态。在Python中,这种情况通常发生在您的代码有错误并引发未捕获的异常时。例如,键入键时,键不再在屏幕上回显,这使使用外壳变得困难。

放在一起:

与第一个示例一起,在程序中实现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())
Run Code Online (Sandbox Code Playgroud)