I have manage to print some data into this format:
GAT Aspartic 36.4597 87663 3.65
CGG Arginine 2.3728 5705 0.24
But as can be observed the 3rd and 4th column are aligned at the left. I achieved this with:
frequency = {'GAT': ['Aspartic', 36.459695863509154, 87663, 0.03645969586350915],
'CGG': ['Arginine', 2.372752072154954, 5705, 0.002372752072154954]}
for codon in frequency.keys():
print "{}\t\t{:14s}\t{:>5.4f}\t\t\t{:6.0f}\t\t{:.2%}\n".format(codon, frequency[codon][0],frequency[codon][1], frequency[codon][2], frequency[codon][3])
Changing it to:
f.write("{}\t\t{:<14s}\t{:<.4f}\t\t\t{:<.0f}\t\t{:.2f}\n".format(...)
Doesn't improve the alignment.
Shouldn't the the first > make it right aligned? I read the documentation but I don't get it.
Could someone explain further the documentation? Thanks
-
2it would be great, if you provide full working example. It shall not be so difficult for the case you describe (and with the skills you have at given reputation you have)Jan Vlcinsky– Jan Vlcinsky2014年05月13日 15:19:25 +00:00Commented May 13, 2014 at 15:19
2 Answers 2
Your problem is, that your columns are too tight. Specifying a longer format (e.g. :>8.4f) gives you a right-aligned output.
answered May 13, 2014 at 15:30
Stefan
2,5181 gold badge19 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
llrs
So if there is not enough space the alignment is omitted? Could you explain this further?
Jan Vlcinsky
you are asking in the format for field 5 characters wide and at the same time require 4 digit after decimal point. This is forcing the result to be wider then 5 characters (otherwise it would trim some leading number) and this breaks the alignment. This is not about ignoring alignment, but about resolving conflicting requirements of the format without breaking final result too much.
Stefan
@Llopis Yes. The problem is, that Python does not know, to which "border" to align, if your data is too long, because the lines are printed separate from each other. As a result, it will simply write, what you wanted and aligns it to the left, because the left "border" is already defined by your current writing position.
how about
frequency = {'GAT': ['Aspartic', 36.459695863509154, 87663, 0.03645969586350915],
'CGG': ['Arginine', 2.372752072154954, 5705, 0.002372752072154954]}
multi = 100
space = 20
for codon in frequency.keys():
row = frequency.get(codon)
values = [codon, row[0], "%.4f" % row[1], str(row[2]), "%.2f"% (row[3]*multi)]
r.write(''.join(map(lambda x: x.rjust(space), values)))
1 Comment
llrs
I should learn about the lambda function but here I can use the string formatting. (also I found that to calculate the percentage is not the pythonic way of doing.)
lang-py