gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:26:55 28 4
gpt4 key购买 nike

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 个字符

最佳答案

使用诅咒

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

read about curses module

您可以使用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()函数将终端恢复到原来的运行模式。

A common problem when debugging a curses application is to get your terminal messed up when the application dies without restoring the terminal to its previous state. In Python this commonly happens when your code is buggy and raises an uncaught exception. Keys are no longer echoed to the screen when you type them, for example, which makes using the shell difficult.

放在一起:

继续第一个例子,在你的程序中实现 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())

关于python - 如何限制 python 上的用户输入长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54952296/

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