Extra spaces when printing

2019-03-06 04:28发布

问题:

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?

回答1:

Yes, format your string:

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


回答2:

You need to format the entire line into a single string, then print that string.

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


回答3:

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...



回答4:

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