首页 > 解决方案 > 在 Python input() 函数中插入分隔符

问题描述

我正在寻找一种在input()函数中插入分隔符的方法。

需要明确的是,我的脚本要求用户在 H:MM:SS 中输入超时,我希望 Python 自己插入:。因此,如果用户键入“14250”,我希望终端显示 1:42:50(在输入期间,而不是在按 ENTER 后)。

在 Python 中可能吗?

标签: pythoninputseparator

解决方案


这是适用于 Linux 的版本。它基于anurag 的版本并且非常相似,但是 Linux 的getch模块不知道getwchand 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,from msvcrt import getwche as getc但我无法对此进行测试。


推荐阅读