-1

I'm printing a simple line program in Python. But when I add a period after a comma in the print statement, I keep seeing a space in between the end of the result and the period. How can I remove this space with a simple print statement?

Code:

print("The sum of 1-9 is",1+2+3+4+5+6+7+8+9,".")

Result:

The sum of 1-9 is 45 .

Desired result:

The sum of 1-9 is 45.
  • 2
    You might find [this](https://stackoverflow.com/questions/5082452/string-formatting-vs-format-vs-f-string-literal) and [this](https://docs.python.org/3/library/functions.html#print) helpful. – medium-dimensional Oct 03 '22 at 18:15

4 Answers4

3

You should get accustomed to using python's f-strings. You could use an f-string to print this statement like this:

print(f"The sum of 1-9 is {1+2+3+4+5+6+7+8+9}.")

The f-string setup will just replace whatever is between the {} with the expression - in this case, it'll do the sum and result in a single number. You can also put in a variable name or any other expression.

scotscotmcc
  • 2,719
  • 1
  • 6
  • 29
  • Thank you! From now on, I'll start using f-strings from now on. They seem like a better option than simple print statements. – Archit Chawla Oct 03 '22 at 18:19
  • @ArchitChawla, you can use them any time you are working with formatting strings, not just when it comes to the final print. For example, you could have `my_string = f"1+2 is {1+2}"`, and this will create the new string called my_string which will have a value of "1+2 is 3". You can then later do `print(my_string)`, but you can also do any other string functions on it or whatever else your heart can imagine. – scotscotmcc Oct 03 '22 at 18:23
2

You could use string formatting:

print("The sum of 1-9 is %s." % str(1+2+3+4+5+6+7+8+9))
Sören Rifé
  • 518
  • 1
  • 4
2

Although I would advise to use an f-string, as said by the other answer, you can use the sep key-word argument to remove the spaces

print("The sum of 1-9 is ",1+2+3+4+5+6+7+8+9,".", sep="")
Tom McLean
  • 5,583
  • 1
  • 11
  • 36
0

The , between the print arguments adds a space.

You can use string concatenation to remove this additional space:

print("The sum of 1-9 is", str(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9) + ".")

Or better yet, try using f-strings:

print(f"The sum of 1-9 is {1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9}.")