0

I've just finished typing up some code for a game I'm working on, however I need to use the "format" function to make the output align properly, I tried using it on this bit of code for example:

 print("    ",humanscore,"    -     ",compscore)

in order to make sure the values of the variables don't shift their position, but it comes up with an error saying "TypeError: format() takes at most 2 arguments (5 given)", So basically I'm just wondering how you use the format function to align lines of code like this. (the spaces inbetween were a cheap way of aligning stuff without the format function. )

3
  • 3
    so... The example code you post doesn't have the format function in it. Did you mean to type format instead of print? Commented May 4, 2015 at 15:09
  • well that's the code originally without any format function in it, I'm trying to understand how you apply it. Commented May 4, 2015 at 15:13
  • is that the actual code you are running that generates your error? It is n't clear, since you are asking about the format function but your example uses the print function...I am guessing print calls format which is unhappy about the extra parameters you passed print. Is that a good summary of your question? Commented May 4, 2015 at 15:16

2 Answers 2

2
print("    {},   -     {}".format(humanscore, compscore))

Assuming your scores are variable and you have this in a for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Note, It's probably unnecessary to call str on the inputs ... format should do that for you.
0

The format method is called on a string and substitutes formatted quantities into the string at places you indicate with markers using braces ({,}). There's a whole mini-language to Python's new(er) string formatting, but for your purposes, to make the scores align you should decide how many characters the maximum score will take up and use '{:<n>d}' where <n> is that maximum. For example if you won't have (integer) scores higher than 999999,

In [8]: humanscore1 = 12
In [9]: compscore1 = 933
In [10]: humanscore2 = 8872
In [11]: compscore2 = 12212

print('{:6d} - {:6d}'.format(humanscore1, compscore1))
print('{:6d} - {:6d}'.format(humanscore2, compscore2))
    12 -    933
  8872 -  12212

To center the numbers instead of aligning them to the right of their fields, use the ^ specifier:

print('{:^6d} - {:^6d}'.format(humanscore2, compscore2))
print('{:^6d} - {:^6d}'.format(humanscore1, compscore1))
 8872  - 12212 
  12   -  933  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.