Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print variables without spaces between values [duplicate]

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?

like image 637
nookonee Avatar asked Feb 23 '15 08:02

nookonee


People also ask

How do you print a variable without spaces between values in Python?

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

How do I get rid of extra spaces in Python print?

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.

How do you print on the same line without space in Python?

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.


2 Answers

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}") 
like image 197
Martijn Pieters Avatar answered Sep 28 '22 08:09

Martijn Pieters


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.

like image 20
Flo Avatar answered Sep 28 '22 09:09

Flo