How to print a string of variables without spaces in Python (minimal coding!)

Question:

I have something like : print "n","|",id,"|",var1,"|",var2,"|",var3,"|",var4,"|"

It prints with spaces for each variable.

| 1 | john | h | johnny | mba |

I want something like this :

|1|john|h|johnny|mba|

I have 20 variables that I have to print and I hate use sys.stdout.write(var) for each one of them. Thanks Pythonistas!

Asked By: ThinkCode

||

Answers:

print "n|%s|%s|%s|%s" % (id,var1,var2,var3,var4)

Take a look at String Formatting.

Edit: The other answers with join are better. Join expects strings.

Answered By: user389875

Try using join:

print "n"+'|'.join([id,var1,var2,var3,var4])

or if the variables aren’t already strings:

print "n"+'|'.join(map(str,[id,var1,var2,var3,var4]))

The benefit of this approach is that you don’t have to build a long format string and it basically works unchanged for an arbitrary number of variables.

Answered By: MAK

For a variable number of values:

print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])
Answered By: Mike Boers

If you are using Python 2.6 or newer, use the new standard for formating string, the str.format method:

print "n{0}|{1}|{2}|".format(id,var1,var2)

link text

Answered By: Steven Mohr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.