Python: print in two columns

牧云@^-^@ 提交于 2019-12-07 02:19:50

问题


I'm trying to print a string with two fixed columns. For example, I'd like to be able to print:

abc       xyz
abcde     xyz
a         xyz

What is the correct way to format the output string when printing to achieve this? Also, how is this done before version 2.6 and after version 2.6?


回答1:


You can use format and mention fix spaces between columns

'{0:10}  {1}'.format(s1, s2)

Old Style formatting

'%-10s' '%s' % (s1,s2)



回答2:


This should work for all lengths of the elements (assuming they are strings. This assumes your data is in two seperate lists first and second.

maxlen = len(max(first, key=len))

for i,j in zip(first, second):
    print "%s\t%s" % (i.ljust(maxlen, " "), j)

This works in Python 2.x, before and after 2.6.




回答3:


Prior to >=python3.6

s1='albha'
s2='beta'

f'{s1}{s2:>10}'

#output
'albha      beta'



回答4:


There are a number of ways of doing this and it depends on how the data is stored. Assumining your data is stored in equal length lists:

for i in range(len(list1)):
    print(“%3i\t%3i” %(list1[i],list2[i]))

This will work in all versions of python. The 3i ensures the output has a field width of 3 characters



来源:https://stackoverflow.com/questions/35236759/python-print-in-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!