Issue
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?
Solution
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}")
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.