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?
To print multiple values or variables without the default single space character in between, use the print() function with the optional separator keyword argument sep and set it to the empty string '' .
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
To print without a new line in Python 3 add an extra argument to your print function telling the program that you don't want your next string to be on a new line. Here's an example: print("Hello there!", end = '') The next print function will be on the same line.
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}")
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.
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