Writing Column Entry Just One Below Another In Python
Solution 1:
If I understand you correctly, you can do something simple like this..
>>>s = '''PAIR 1MFK 1 URANIUM 82 HELIUM 112 3.6997 ...PAIR 2JGH 2 PLUTONIUM 98 POTASSIUM 88 5.3003 ...PAIR 345G 3 SODIUM 23 CARBON 14 1.664 ...PAIR 4IG5 4 LITHIUM 82 ARGON 99 2.5506'''>>>ll = [x.split() for x in s.split('\n')]>>>for row in ll:...print''.join(x.ljust(10) for x in row)...
PAIR 1MFK 1 URANIUM 82 HELIUM 112 3.6997
PAIR 2JGH 2 PLUTONIUM 98 POTASSIUM 88 5.3003
PAIR 345G 3 SODIUM 23 CARBON 14 1.664
PAIR 4IG5 4 LITHIUM 82 ARGON 99 2.5506
Here I am using a fixed column width of 10 characters. If you like, you can make it slightly more sophisticated by calculating appropriate column widths beforehand.
>>>column_widths = [max(len(x) for x in l) for l inzip(*ll)]>>>for row in ll:...print' '.join(x.ljust(w) for x,w inzip(row, column_widths))...
PAIR 1MFK 1 URANIUM 82 HELIUM 112 3.6997
PAIR 2JGH 2 PLUTONIUM 98 POTASSIUM 88 5.3003
PAIR 345G 3 SODIUM 23 CARBON 14 1.664
PAIR 4IG5 4 LITHIUM 82 ARGON 99 2.5506
Solution 2:
If you don't have too many lists, you could do something like this:
lst1 = ['PAIR','1MFK','1','URANIUM','82','HELIUM','112','3.6997']
lst2 = 'PAIR 2JGH 2 PLUTONIUM 98 POTASSIUM 88 5.3003'.split(' ')
lst3 = 'PAIR 345G 3 SODIUM 23 CARBON 14 1.664'.split(' ')
lst4 = 'PAIR 4IG5 4 LITHIUM 82 ARGON 99 2.5506'.split(' ')
lsts = [lst1, lst2, lst3, lst4]
sizes = [max(len(item) for item in l) + 2 for l in zip(*lsts)]
for lst in lsts:
print"".join(word.ljust(sizes[i]) for i, word in enumerate(lst))
OUTPUT
PAIR 1MFK 1 URANIUM 82 HELIUM 1123.6997
PAIR 2JGH 2 PLUTONIUM 98 POTASSIUM 885.3003
PAIR 345G 3 SODIUM 23CARBON141.664
PAIR 4IG5 4 LITHIUM 82 ARGON 992.5506
The benefit of this approach is that you don't have to guess how much you need to pad by.
Solution 3:
I am assuming each line of input becomes a list (lst
) for processing. Inside your processing loop you could use formatting directives with your print to line up the output.
Given your current input line/lst
:
lst = ['PAIR', '1MFK', 'URANIUM', '82', 'HELIUM', '112', '3.6997']
final = ' '.join(lst)
then:
print('%8s %8s %10s %4s %10s %5s %10s' % (tuple(final.split())))
You could adjust the field widths to suit your needs.
If you needed numbers to line up you could convert the strings into numbers via int()
or float()
and then use the appropriate formatting directives to line up the decimal points, for instance using %7.4f
for your floats, and %4d
for your ints (again, pick values that meet your needs)
Post a Comment for "Writing Column Entry Just One Below Another In Python"