How to print a string of variables without spaces

2019-02-25 10:19发布

问题:

This question already has an answer here:

  • How to print variables without spaces between values [duplicate] 6 answers

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!

回答1:

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.



回答2:

For a variable number of values:

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


回答3:

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.



回答4:

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