How to deeply join a tuple in a string

I want to convert a tuple to a comma delimited string. Easy.

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

Output:

 '1;2' 

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

 '1;(2, 3)' 

I do not want this comma, I want a semicolon, and I would also like to select the characters in parentheses.

I want this:

 '1;{2;3}' 

Is there an easy way to deeply combine tuples of tuples nested at any depth, with both the delimiter (';' in the example) and the brackets ('{' and '}' in the example above)?

Note that I do not want this, that this question has been marked as a duplicate:

 '1,2,3' 

I also need to process strings with commas in them, so I cannot use replace :

 flatten((1,('2,3',4))) '1;{2,3;4}' 
+8
python
source share
1 answer

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) 

Using:

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

All Articles