How to print variables without spaces between values [duplicate] How to print variables without spaces between values [duplicate] python python

How to print variables without spaces between values [duplicate]


Don't use print ..., (with a trailing comma) if you don't want spaces. Use string concatenation or formatting.

Concatenation:

print 'Value is "' + str(value) + '"'

Formatting:

print 'Value is "{}"'.format(value)

The latter is far more flexible, see the str.format() method documentation and the Formatting String Syntax section.

You'll also come across the older % formatting style:

print 'Value is "%d"' % valueprint 'Value is "%d", but math.pi is %.2f' % (value, math.pi)

but this isn't as flexible as the newer str.format() method.

In Python 3.6 and newer, you'd use a formatted string (f-string):

print(f"Value is {value}")


Just an easy answer for the future which I found easy to use as a starter:Similar to using end='' to avoid a new line, you can use sep='' to avoid the white spaces...for this question here, it would look like this: print('Value is "', value, '"', sep = '')

May it help someone in the future.


It's the comma which is providing that extra white space.

One way is to use the string % method:

print 'Value is "%d"' % (value)

which is like printf in C, allowing you to incorporate and format the items after % by using format specifiers in the string itself. Another example, showing the use of multiple values:

print '%s is %3d.%d' % ('pi', 3, 14159)

For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print call:

>>> print(1,2,3,4,5)1 2 3 4 5>>> print(1,2,3,4,5,end='<<\n')1 2 3 4 5<<>>> print(1,2,3,4,5,sep=':',end='<<\n')1:2:3:4:5<<