简体   繁体   中英

How to deep join a tuple into a string

I want to convert a tuple to a semicolon-separated string. Easy.

tup = (1,2)
';'.join(map(str,tup))

Output:

'1;2'

If one of the tuple entries is itself a tuple, however, I get something like this:

'1;(2, 3)'

I don't want that comma, I want a semicolon, and also I'd like to select the parentheses characters as well.

I want this:

'1;{2;3}'

Is there an easy way to deep-join a tuple of tuples nested to any depth, specifying both the separator (';' in the example) and the parenthes ('{' and '}' in the example above)?

Note that I do not want this, which this question was marked as a duplicate of:

'1,2,3'

I also need to handle strings with commas in them, so i can't use replace :

flatten((1,('2,3',4)))
'1;{2,3;4}'

Recursion to the rescue!

def jointuple(tpl, sep=";", lbr="{", rbr="}"):
    return sep.join(lbr + jointuple(x) + rbr if isinstance(x, tuple) else str(x) for x in tpl)

Usage:

>>> jointuple((1,('2,3',4)))
'1;{2,3;4}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM