61

I would like to know how to remove additional spaces when I print something.

Like when I do:

print 'Value is "', value, '"'

The output will be:

Value is " 42 "

But I want:

Value is "42"

Is there any way to do this?

0

6 Answers 6

82

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"' % value
print '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}")
Sign up to request clarification or add additional context in comments.

3 Comments

Oh okay I didn't know that, just learning Python, thanks for the quick answer !
''.format style is preferable because it avoids several %-style related edge cases such as implicit promotion to unicode and unintentional % tuple, % dict usage.
@J.F.Sebastian: not to mention that str.format() supports custom formatting for classes; you cannot easily format datetime objects with % the way you can with str.format(), for example. Then there is the recursive field definitions (you can use fields to determine how other fields are formatted), etc.
61

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.

4 Comments

Thank you! this has helped me with an issue that's been bugging me for ages
This is python 3 specific syntax.
Super useful tip
Found very useful when trying to use ternary conditional operators in a print statement, thanks
16

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<<

6 Comments

the % interpolation is prone to errors with tuples and other peculiar behaviour.
And yet, somehow, I managed to cobble together the code and have it work first time. Yes, you have to know about the shortcomings of the tools you use. That's true in any field. I'm not the type of developer that tends to pass arbitrary types to my formatting operations :-)
that is why the .format that works without any edge cases on 99.999 % of Python installations a new user can come across, is the more newbie friendly soution-
@Antti. Err, just out interest, what's the other 0.001%? Or was that just reticence to claim certainty? Not that I have an issue with that, I've done it before myself.
It means, someone might be learning Python to maintain a solution that runs and is stuck to <= 2.5, or maybe Jython 2.5.
|
4

https://docs.python.org/2/library/functions.html#print

print(*objects, sep=' ', end='\n', file=sys.stdout)

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

from future import print_function

Comments

2

To build off what Martjin was saying. I'd use string interpolation/formatting.

In Python 2.x which seems to be what you're using due to the lack of parenthesis around the print function you do:

print 'Value is "%d"' % value

In Python 3.x you'd use the format method instead, so you're code would look like this.

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

Comments

-1
>>> value=42

>>> print "Value is %s"%('"'+str(value)+'"') 

Value is "42"

2 Comments

No need to have the extra concatenation just to get the " characters
User repr or, in this case %r

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.