Python:打印跨越给定宽度的字符串,但第一部分左对齐,第二部分右对齐

时间:2016-08-23 11:58:44

标签: python string format text-alignment

我想输出类似的内容:

===>>> [FINISHED] Building sources: bla                               (1h:20m:30s)
===>>> [FINISHED] Building sources: The brown fox jumped...           (7h:05m:00s)

即填充宽度为N个字符的字符串,第一部分左对齐,第二部分右对齐。

我在函数中有一个print,我只想获得一个易于阅读的输出。在脚本执行结束时,我会看到几行,如上所述。

更多评论:

  • 字符串的两个部分永远不会超过N
  • N是一个常数值。
  • 我已经有了两个字符串,我不需要任何约会 格式化。

使用Python的字符串格式是否可以通用的方式执行此操作?类似的东西:

N=80
first_part_of_the_string  = "===>>> [FINISHED] Building sources: " + some_random_text
second_part_of_the_string = my_function_to_convert_time_to_hms(time)

print("{<}{:N>}".format(first_part_of_the_string, second_part_of_the_string))

2 个答案:

答案 0 :(得分:2)

假设您知道线条的宽度,您可以使用<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' rel='stylesheet' type='text/css'> 将字符串填充到带有空格的n长度。如果字符串长于n,则不会缩短字符串,因为状态永远不会是这种情况。

'{:n}'.format(string)

以类似的方式,你可以用零填充来格式化时间:'===>>> [FINISHED] Building sources: {:35} ({})'.format('bla', 'time')

{:02}

印刷

hour = 1
minute = 20
second = 30
prefix = '===>>> [FINISHED] Building sources: '
content = 'bla'

time = '({:02}h:{:02}m:{:02}s)'.format(hour, minute, second)
print '{}{:35} {}'.format(prefix, content, time)

答案 1 :(得分:0)

只需一种方法,添加正确数量的空格......

>>> for a, b in ('fsad', 'trwe'), ('gregrfgsd', '5435234523554'):
        print a + ' ' * (50 - len(a + b)) + b

fsad                                          trwe
gregrfgsd                            5435234523554