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!

0

4 Answers 4

7

For a variable number of values:

print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])
Sign up to request clarification or add additional context in comments.

3 Comments

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

Comments

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.

2 Comments

%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.
Of course %s doesn't give terribly useful output unless __str__ or __repr__ are implemented
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

1 Comment

And if you have Python 2.7 or newer, you can even drop the numbers: "\n{}|{}|{}|".format(id, var1,var2)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.