Extra spaces when printing

2019-03-06 04:09发布

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?

4条回答
仙女界的扛把子
2楼-- · 2019-03-06 04:27

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楼-- · 2019-03-06 04:28

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

查看更多
仙女界的扛把子
4楼-- · 2019-03-06 04:29

Yes, format your string:

print("... you guessed {}, and ... was {}!".format(math_guess, math_score))
查看更多
做自己的国王
5楼-- · 2019-03-06 04:33
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...

查看更多
登录 后发表回答