[英]Python: print a string spanning to a given width, but first part left-aligned and second part right-aligned
I would like to output something like: 我想输出类似:
===>>> [FINISHED] Building sources: bla (1h:20m:30s)
===>>> [FINISHED] Building sources: The brown fox jumped... (7h:05m:00s)
That is, a string filling a width of N
characters, with a first part left-aligned, and a second part right-aligned. 即,一个字符串填充
N
字符的宽度,第一部分左对齐,第二部分右对齐。
I have a print
in a function and I just want to get an easy-to-read output. 我在函数中有一个
print
,我只想获得一个易于阅读的输出。 At the end of the execution of the script, I will see a few lines like the ones above. 在脚本执行的最后,我将看到几行类似于上面的几行。
Some more comments: 更多评论:
N
. N
N
is a constant value. N
为常数。 Is it posible to do this using Python's string `format ìn a generic way? 是否可以通过通用的方式使用Python的字符串`format'来做到这一点? Something like:
就像是:
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))
assuming you know the width of the line you can use '{:n}'.format(string)
to fill the string up to n-length with spaces. 假设您知道行的宽度,则可以使用
'{:n}'.format(string)
将字符串填充为n个长度的空格。 This does not shorten the string if it is longer than n, as you state will never be the case. 如果字符串长于n,则不会缩短字符串,因为您声明永远不会这样。
'===>>> [FINISHED] Building sources: {:35} ({})'.format('bla', 'time')
in a similar fashion you can format the time by padding with zeroes: {:02}
您可以用类似的方式通过用零填充来格式化时间:
{: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)
printing 印刷
'===>>> [FINISHED] Building sources: bla (01h:20m:30s)'
Just one way, adding the right number of spaces... 仅一种方法,添加正确数量的空格...
>>> for a, b in ('fsad', 'trwe'), ('gregrfgsd', '5435234523554'):
print a + ' ' * (50 - len(a + b)) + b
fsad trwe
gregrfgsd 5435234523554
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.