【问题标题】:Insert separator in Python input() function在 Python input() 函数中插入分隔符
【发布时间】:2021-01-15 12:29:17
【问题描述】:

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

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

在 Python 中可以吗?

【问题讨论】:

  • 可能不是input,可能是通过读取和回显单个字符,或者使用curses
  • 纯 Python 在用户提交输入之前无法看到正在输入的内容,因此您必须使用特定于操作系统的东西,例如 curses。
  • 好的,我会这样看,谢谢你的回答!

标签: python input separator


【解决方案1】:

这是适用于 Linux 的版本。它基于version by anurag 并且非常相似,但是Linux 的getch 模块不知道getwchputwch,所以必须替换它们。

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

认为这也适用于带有from msvcrt import getwche as getc 的 Windows,但我无法对此进行测试。

【讨论】:

    【解决方案2】:

    有一种方法可以实现结果(某种程度上),在 Windows 10,Python 3.7 上测试:

    import msvcrt as osch
    
    def main():
        timestr = ''
        print('Enter time in 24-hr format (hh:mm:ss): ', end='', 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 小时,这意味着用户需要输入 014923 而不是 14923

    【讨论】:

    • 在 Python 3.7 上测试,控制台。不确定它是否适用于 IPython/Jupyter-Notebook。
    • 获取“没有属性getwch”,对于Python 3.8.5、getch 1.0、Ubuntu 20.04 (Linux) 也没有putwch(或任何put...
    • 通过一些修改它可以工作,但是,例如您可以将 putwch 替换为 print 并在 LInux 上使用 getche
    • @tobias_k 我在 windows 上测试过我的(是的,我知道)所以我只会在 windows 上做我的答案,你能添加 linux 的答案吗,因为你可以测试也一样?
    • 如果你不介意的话,我会把它添加到你的。然后,您可以检查是否同样适用于 Windows 以获得适合两者的版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多