Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add space between two variables after a print in Python

I'm fairly new to Python, so I'm trying my hand at some simple code. However, in one of the practices my code is supposed to display some numbers in inches on the left and the conversion of the numbers on the right;

count = 1
conv = count * 2.54
print count, conv

I want the output to be printed with some space between them;

count = 1
conv = count * 2.54
print count,     conv

I can't figure out how to do this. I've searched everywhere, but all I can find are people trying to get rid of space. If someone could just lead me in the right direction, I'd be thankful.

Oh, and I just realized that I'm using Python 2.7, not 3.x. Not sure if this is important.

like image 404
Hebon Avatar asked Apr 02 '12 00:04

Hebon


People also ask

How do I add a space between printed lines in Python?

You have a few solutions: The simpler one would be to use a print statement between your lines, which, used alone, prints a line feed. Alternatively, you could you end the string you're printing with a '\n' character, which will cause a line feed, or you could start your input with the same character.

How do you print numbers with spaces in Python?

To give multiple spaces between two values, we can assign space in a variable, and using the variable by multiplying the value with the required spaces. For example, there is a variable space assigned with space and we need to print 5 spaces - we can use space*5 and it will print the 5 spaces.


2 Answers

A simple way would be:

print str(count) + '  ' + str(conv)

If you need more spaces, simply add them to the string:

print str(count) + '    ' + str(conv)

A fancier way, using the new syntax for string formatting:

print '{0}  {1}'.format(count, conv)

Or using the old syntax, limiting the number of decimals to two:

print '%d  %.2f' % (count, conv)
like image 61
Óscar López Avatar answered Sep 22 '22 18:09

Óscar López


Use string interpolation instead.

print '%d   %f' % (count,conv)
like image 34
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 18:09

Ignacio Vazquez-Abrams