3

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?

amin
  • 429
  • 4
  • 8
  • 15
  • can you post the code? – Alvaro Oct 03 '13 at 15:05
  • sorry.. assignment code. we r not allowed to post. – amin Oct 03 '13 at 15:06
  • 1
    I am sure you are not allowed to ask for assignment answers either. – sPaz Oct 03 '13 at 15:10
  • None of the fields in your sample output show right justification. Maybe you didn't post using ``? Otherwise you don't need any formatting, it looks like you just need to print a bunch of values. – cdarke Oct 03 '13 at 15:10
  • @sPaz just asking for a solution to a simple logic. this is a general question. please try to understand and not create unnecessary conflict – amin Oct 03 '13 at 15:57
  • @cdarke sorry the code did not print properly – amin Oct 03 '13 at 15:57
  • @cdarke hello nice bye and well are supposed to be in new lines with their respective values – amin Oct 03 '13 at 15:58
  • @cdarke ok man, got it fixed. i want the output to be aligned like this, however, the numbers are not aligned if they have different number of digits – amin Oct 03 '13 at 16:01
  • @amin are the numbers in a list or something? – sPaz Oct 03 '13 at 17:27
  • `{0:>7}` isn't good as a format because it doesn't have a type e.g. `{0:>7d}` – smci Feb 23 '18 at 18:55

1 Answers1

9

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)
Alvaro
  • 11,797
  • 9
  • 40
  • 57
  • i tried this, but it gives me the same output. how does this alignment system in python work? – amin Oct 03 '13 at 16:02