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.
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.
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.
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)
Use string interpolation instead.
print '%d %f' % (count,conv)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With