4

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!

ThinkCode
  • 7,841
  • 21
  • 73
  • 92

4 Answers4

7

For a variable number of values:

print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])
Mike Boers
  • 6,665
  • 3
  • 31
  • 40
6

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.

MAK
  • 26,140
  • 11
  • 55
  • 86
5
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.

user389875
  • 71
  • 4
  • 1
    `%s` works with any object, not just strings -- `"%s + %s" % (1, 2) == "1 + 2"`. You don't have to use `%d` unless you want the code to throw an exception for non-numeric input. – John Millikin Jul 14 '10 at 20:04
  • Of course %s doesn't give terribly useful output unless `__str__` or `__repr__` are implemented – Wayne Werner Jul 14 '10 at 20:10
2

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

Steven Mohr
  • 1,167
  • 6
  • 19