简体   繁体   中英

Extra spaces when printing

I've read through a number of the python whitespace removal questions and answers but haven't been able to find what I'm looking for. Here is a small program that shows a specific example of the issue. I greatly appreciate your help.

import random

math_score = random.randint(200,800)
math_guess = int(input("\n\nWhat score do you think you earned on the math section (200 to 800)?\t"))
print ("\n\n\nOn the math section, you guessed",math_guess,", and your actual score was",math_score,"!")

So here's my issue:

When I execute the program, I get the following results:

On the math section, you guessed 600 , and your actual score was 717 !

I would like to remove the space that follows each variable in the sentence. In this case the space between 600 and the "," and the space between 717 and the "!".

Is there a standard way to approach this issue?

是的, 格式化您的字符串:

print("... you guessed {}, and ... was {}!".format(math_guess, math_score))

您需要将整行格式化为单个字符串,然后打印该字符串。

print ("\n\n\nOn the math section, you guessed {0}, and your actual score was {1}!".format(math_guess, math_score))
print ("\n\n\nOn the math section, you guessed",math_guess,", and your actual score was",math_score,"!", sep ='')

if this is py3+ i think

print ("\n\n\nOn the math section, you guessed"+str(math_guess)+", and your actual score was"+str(math_score)+"!")

should work if not

or use string formatting as others have suggested...

Try this one:

print "\n\n\nOn the math section, you guessed %d and your actual score was %d!" % (math_guess, math_score)

You can read more at Built-in Types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM