【问题标题】:Format console output in Python to have fixed width在 Python 中将控制台输出格式化为具有固定宽度
【发布时间】:2020-03-29 09:23:54
【问题描述】:

我正在构建一个 CLI,并希望将我的输出格式化为最大 60 个字符宽。我不想连字符,但是如果单词太长并且不想在我的文本中手动插入\n 字符来实现这个目标,请将它移到下一行。我一直在玩 Pthons .format() 函数,但无济于事。

示例:输出中的行应在 'blurry' 之后结束:

===================== IMAGE-DELETE CLI =====================


Welcome to the IMAGE-DELETE CLI. Based on your input blurry and under / overexposed images will be deleted and to free up some disk space.


Lets get started...

【问题讨论】:

    标签: python-3.x output command-line-interface string-formatting


    【解决方案1】:

    使用textwrap 模块。

    import textwrap
    
    lines = textwrap.wrap(text, width=60) # text is the variable contains what you want to print out
    
    # then print it out
    for line in lines:
        print(line)
    

    希望这会有所帮助。在此处查看更多信息:https://docs.python.org/3/library/textwrap.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 2011-10-15
      • 2012-01-15
      • 1970-01-01
      • 2014-05-24
      相关资源
      最近更新 更多