【问题标题】:Format text output [duplicate]格式化文本输出[重复]
【发布时间】:2015-07-20 10:52:26
【问题描述】:
def formatWords(words):
  result = "Word List:\tWord Count:\n"
  for i in words:
    result += i + ":\t" + str(words.count(i)) + "\n"
  return result

words 只是一个字符串数组。

我应该得到一个输出

我得到了

的输出

如何将字符串格式化为看起来像第一张图片?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

使用字符串方法ljust()

result += (i+':').ljust(20) + str(words.count(i)) + '\n'

20 是该字符串的总大小,需要填充许多空格才能达到该大小。

【讨论】:

    【解决方案2】:

    示例 1:

    row_format = "{:<15}" * 2
    rows = [('word list:', 'word_count'),
            ('brown', 1),
            ('dog', 1)]
    for row in rows:
        print row_format.format(*row)
    

    输出:

    word list:     word_count     
    brown          1              
    dog            1     
    

    示例 2:

    row_format = "{:<15}{:^15}"
    rows = [('word list:', 'word_count'),
            ('brown', 1),
            ('dog', 1)]
    for row in rows:
        print row_format.format(*row)  
    

    输出:

    word list:       word_count   
    brown                 1       
    dog                   1     
    

    Format Specification Mini-Language提供更多细节。

    【讨论】:

      【解决方案3】:

      使用format 函数。

      result += "{:<20}{:<30}\n".format(i, words.count(i))
      

      【讨论】:

        猜你喜欢
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-27
        • 2014-09-30
        相关资源
        最近更新 更多