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

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

It prints with spaces for each variable.

| 1 | john | h | johnny | mba |

I need something like this:

|1|john|h|johnny|mba|

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

+3
source share
4 answers

Try using join:

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

or if the variables are no longer strings:

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

The advantage of this approach is that you do not need to create a long formatted string, and it practically does not change for an arbitrary number of variables.

+6
source

For a variable number of values:

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

.

Edit: other answers with joining are better. Join awaits the line.

+5
source

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

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

link text

+2
source

Source: https://habr.com/ru/post/1754680/


All Articles