python 3 string formatting (alignment)

旧时模样 提交于 2020-06-28 02:39:31

问题


i have a code where the out put should be like this:

    hello   3454
    nice     222
    bye    45433
    well    3424

the alignment and right justification is giving me problems. i tried this in my string {0:>7} but then only the numbers with the specific amount of digits are alright. the other numbers that have some digits more or less become messed up. it is very obvious to understand why they are messing up, but i am having trouble finding a solution. i would hate to use constant and if statements all over the place only for such a minor issue. any ideas?


回答1:


You could try:

"{:>10d}".format(n) where n is an int to pad-left numbers and

"{:>10s}".format(s), where s is a string to pad-left strings

Edit: choosing 10 is arbitrary.. I would suggest first determining the max length.

But I'm not sure this is what you want.. Anyways, this link contains some info on string formatting:

String formatting

You can try this:

def align(word, number):
    return "{:<10s}{:>10d}".format(word, number)

This will pad-right your string with 10 spaces and pad-left your number with 10 spaces, giving the desired result Example:

align('Hello', 3454)
align('nice', 222)
align('bye', 45433)
align('well', 3424)


来源:https://stackoverflow.com/questions/19162621/python-3-string-formatting-alignment

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