【问题标题】:Python - Place a character in between a formatted stringPython - 在格式化字符串之间放置一个字符
【发布时间】:2018-05-07 23:22:32
【问题描述】:

假设我想打印出来

Item 1           |         Item 2
A Third item     |             #4

这可以在没有 | 的情况下完成通过做

print('%s20  %20s' % (value1,value2))

我将如何放置 |字符,以便在两个格式化值之间均匀对齐?

我想我可以手动获取格式化字符串的长度,而不需要 |字符,然后插入 |在中间,但我希望有一个更优雅的解决方案!

非常感谢您的宝贵时间。

编辑:这是我建议的可行解决方案

def PrintDoubleColumn(value1, value2):
  initial =  '%s20  %20s' % (value1,value2)
  lenOfInitial = len(initial)
  print(initial[:lenOfInitial/2] +'|' + initial[lenOfInitial/2+1:])

【问题讨论】:

标签: python string format center text-alignment


【解决方案1】:

string format operations有一个很好的来源:https://pyformat.info/#string_pad_align

x = [1, 2, 3, 4, 5]
y = ['a', 'b', 'c', 'd', 'e']

for i in range(0, 5):
    print "{0:<20}|{1:>20}".format(x[i], y[i])

结果:

1                    |                    a
2                    |                    b
3                    |                    c
4                    |                    d
5                    |                    e

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2011-07-28
    • 1970-01-01
    相关资源
    最近更新 更多