Anthony Perez
Anthony Perez

Reputation: 1593

How do I prevent spaces when using Python?

How would I remove the spaces after the R in the following line?

>>>print "4/3 =", 4 / 3, "R", 4 % 3

I want the result to look exactly like this:

4/3 = 1 R1

I appreciate any time anyone takes to answer this question.

Upvotes: 1

Views: 91

Answers (3)

Green Su
Green Su

Reputation: 2348

You should use string format

print "4/3 =%d R%d" % (4 / 3, 4 % 3)

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838256

Use str.format:

>>> a=4
>>> b=3
>>> print "{}/{} = {} R{}".format(a, b, a//b, a%b)
4/3 = 1 R1

If you are using an older version of Python which doesn't support str.format then you can use the % operator:

>>> print "%d/%d = %d R%d"%(a, b, a//b, a%b)
4/3 = 1 R1

Note also that since Python 2.2 you should use // for integer division, and from Python 3 onwards, you must use //.

Upvotes: 7

iTayb
iTayb

Reputation: 12743

You should use formatting.

print "4/3 = %d R%d" % (4 / 3, 4 % 3)

or even better, with string.format:

print "4/3 = {} R{}".format(4 / 3, 4 % 3)

Upvotes: 0

Related Questions