Skip to content Skip to sidebar Skip to footer

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 problem

Solution 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:

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

Post a Comment for "Python 3 String Formatting (alignment)"