简体   繁体   中英

String formatting alignment

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

Your problem is, that your columns are too tight. Specifying a longer format (eg :>8.4f ) gives you a right-aligned output.

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM