问题
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