如何解决在 Python input() 函数中插入分隔符
我正在寻找一种在 input()
函数中插入分隔符的方法。
明确地说,我的脚本要求用户在 H:MM:SS 中输入超时,我希望 Python 自己插入 :
。
因此,如果用户键入“14250”,我希望终端显示 1:42:50(在输入期间,而不是在按 ENTER 之后)。
在 Python 中可以吗?
解决方法
这是一个适用于 Linux 的版本。它基于 version by anurag 并且非常相似,但 Linux 的 x := x + 1
模块不知道 getch
和 getwch
,因此必须替换它们。
putwch
示例输出:
from getch import getche as getc
def gettime():
timestr = ''
print('Enter time in 24-hr format (hh:mm:ss): ',end='',flush=True)
for i in range(6):
timestr += getc() # get and echo character
if i in (1,3): # add ":" after 2nd and 4th digit
print(":",end="",flush=True)
timestr += ':'
print() # complete the line
return timestr
time = gettime()
print("The time is",time)
我认为这也适用于带有 Enter time in 24-hr format (hh:mm:ss): 12:34:56
The time is 12:34:56
的 Windows,但我无法对此进行测试。
有一种方法可以实现结果(在某种程度上),在 Windows 10、Python 3.7 上测试:
import msvcrt as osch
def main():
timestr = ''
print('Enter time in 24-hr format (hh:mm:ss): ',flush=True)
for i in range(6):
ch = osch.getwch()
if i!=0 and i%2==0:
osch.putwch(':')
timestr += ':'
osch.putwch(ch)
timestr += ch
return timestr
if __name__ == "__main__":
res = main()
print('\n')
print(res)
请注意,创建变量 timestr
只是为了存储以备将来使用。此外,您可以应用各种有效性检查。在我看来,此方法不能用于将 14923
类型的时间输入解析为 1:49:23
,因为前瞻不可用并且无法知道用户是否要输入 12 小时时间或 24 小时时间。我将使用 24 小时时间,这意味着用户需要输入 14923
而不是 014923
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。