views:

79

answers:

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!

+4  A: 
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.

`%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
Fixed. Thank you.
Of course %s doesn't give terribly useful output unless `__str__` or `__repr__` are implemented
Wayne Werner
+5  A: 

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
+6  A: 

For a variable number of values:

print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])
Mike Boers
print '|%s|' % '|'.join(map(str, [id, var1, var2, var3, var4])) looks better (if you have really big array you can use imap instead).
Tomasz Wysocki
@Tomasz: You think so? I thought that Pythonistas normally consider the generator clearer...
Mike Boers
You may be right. But in this approach map seams to be useless.
Tomasz Wysocki
A: 

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
And if you have Python 2.7 or newer, you can even drop the numbers: `"\n{}|{}|{}|".format(id, var1,var2)`
Tim Pietzcker