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

12,891

Solution 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.

Solution 2

For a variable number of values:

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

Solution 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.

Solution 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

Share:
12,891

Related videos on Youtube

ThinkCode
Author by

ThinkCode

Updated on June 04, 2022

Comments

  • ThinkCode
    ThinkCode almost 2 years

    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!

  • John Millikin
    John Millikin almost 14 years
    %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.
  • Tim Pietzcker
    Tim Pietzcker almost 14 years
    And if you have Python 2.7 or newer, you can even drop the numbers: "\n{}|{}|{}|".format(id, var1,var2)
  • Wayne Werner
    Wayne Werner almost 14 years
    Of course %s doesn't give terribly useful output unless __str__ or __repr__ are implemented
  • Tomasz Wysocki
    Tomasz Wysocki almost 14 years
    print '|%s|' % '|'.join(map(str, [id, var1, var2, var3, var4])) looks better (if you have really big array you can use imap instead).
  • Mike Boers
    Mike Boers almost 14 years
    @Tomasz: You think so? I thought that Pythonistas normally consider the generator clearer...
  • Tomasz Wysocki
    Tomasz Wysocki almost 14 years
    You may be right. But in this approach map seams to be useless.

Related