Python - convert list of tuples to string

后端 未结 7 1449
执笔经年
执笔经年 2020-12-05 10:50

Which is the most pythonic way to convert a list of tuples to string?

I have:

[(1,2), (3,4)]

and I want:

\"(1,2), (         


        
相关标签:
7条回答
  • 2020-12-05 11:07

    you might want to use something such simple as:

    >>> l = [(1,2), (3,4)]
    >>> str(l).strip('[]')
    '(1, 2), (3, 4)'
    

    .. which is handy, but not guaranteed to work correctly

    0 讨论(0)
  • 2020-12-05 11:11

    You can try something like this (see also on ideone.com):

    myList = [(1,2),(3,4)]
    print ",".join("(%s,%s)" % tup for tup in myList)
    # (1,2),(3,4)
    
    0 讨论(0)
  • 2020-12-05 11:12

    The most pythonic solution is

    tuples = [(1, 2), (3, 4)]
    
    tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
    
    result = ', '.join(tuple_strings)
    
    0 讨论(0)
  • 2020-12-05 11:13

    How about

    l = [(1, 2), (3, 4)]
    print repr(l)[1:-1]
    # (1, 2), (3, 4)
    
    0 讨论(0)
  • 2020-12-05 11:13

    I think this is pretty neat:

    >>> l = [(1,2), (3,4)]
    >>> "".join(str(l)).strip('[]')
    '(1,2), (3,4)'
    

    Try it, it worked like a charm for me.

    0 讨论(0)
  • 2020-12-05 11:15

    How about:

    >>> tups = [(1, 2), (3, 4)]
    >>> ', '.join(map(str, tups))
    '(1, 2), (3, 4)'
    
    0 讨论(0)
提交回复
热议问题