Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3 string formatting (alignment)

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?

like image 600
amin Avatar asked Jul 14 '26 21:07

amin


1 Answers

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)
like image 103
Alvaro Avatar answered Jul 16 '26 09:07

Alvaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!