formatting list -> comma separated

Discussion in 'Python' started by Robert, Jul 9, 2008.

  1. Robert

    Robert Guest

    given d:

    d = ["soep", "reeds", "ook"]

    I want it to print like

    soep, reeds, ook

    I've come up with :

    print ("%s"+", %s"*(len(d)-1)) % tuple(d)

    but this fails for d = []

    any (pythonic) options for this?

    Robert
    Robert, Jul 9, 2008
    #1
    1. Advertising

  2. Robert

    Jerry Hill Guest

    On Wed, Jul 9, 2008 at 3:23 PM, Robert <> wrote:
    > given d:
    > d = ["soep", "reeds", "ook"]
    >
    > I want it to print like
    > soep, reeds, ook


    use the join() method of strings, like this:
    >>> d = ["soep", "reeds", "ook"]
    >>> ', '.join(d)

    'soep, reeds, ook'
    >>> d = []
    >>> ', '.join(d)

    ''
    >>>


    --
    Jerry
    Jerry Hill, Jul 9, 2008
    #2
    1. Advertising

  3. Robert

    Paul Hankin Guest

    On Jul 9, 8:23 pm, "Robert" <> wrote:
    > given d:
    >
    > d = ["soep", "reeds", "ook"]
    >
    > I want it to print like
    >
    > soep, reeds, ook
    >
    > I've come up with :
    >
    > print ("%s"+", %s"*(len(d)-1)) % tuple(d)
    >
    > but this fails for d = []
    >
    > any (pythonic) options for this?


    print ', '.join(d)

    --
    Paul Hankin
    Paul Hankin, Jul 9, 2008
    #3
  4. Robert

    norseman Guest

    Robert wrote:
    > given d:
    >
    > d = ["soep", "reeds", "ook"]
    >
    > I want it to print like
    >
    > soep, reeds, ook
    >
    > I've come up with :
    >
    > print ("%s"+", %s"*(len(d)-1)) % tuple(d)
    >
    > but this fails for d = []
    >
    > any (pythonic) options for this?
    >
    > Robert
    >
    >
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >

    ================================
    the old fashion way would be:

    d = ["soep", "reeds", "ook"]
    if len(d) > 0:
    print ("%s"+", %s"*(len(d)-1)) % tuple(d)

    # if d= [] then print stmnt bypassed



    Steve
    norseman, Jul 10, 2008
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jason Miles
    Replies:
    1
    Views:
    602
    Jürgen Exner
    May 28, 2004
  2. Peter Rilling

    Array to a comma Separated String

    Peter Rilling, Jul 8, 2004, in forum: ASP .Net
    Replies:
    3
    Views:
    505
  3. Replies:
    9
    Views:
    4,459
    nader
    Apr 16, 2011
  4. Michiel Overtoom
    Replies:
    1
    Views:
    335
    Niklas Norrthon
    Jul 22, 2008
  5. Christina
    Replies:
    26
    Views:
    469
    Dave Anderson
    Feb 2, 2004
Loading...

Share This Page