Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep join a tuple into a string

Tags:

python

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}'
like image 763
PhilHibbs Avatar asked Dec 13 '17 14:12

PhilHibbs


People also ask

How do you join a tuple to a string?

Use the str. join() Function to Convert Tuple to String in Python. The join() function, as its name suggests, is used to return a string that contains all the elements of sequence joined by an str separator. We use the join() function to add all the characters in the input tuple and then convert it to string.

Can you use join on tuple?

The join function can be used to join each tuple elements with each other and list comprehension handles the task of iterating through the tuples.

Which function converts tuple to string?

join() The join() method is a string method and returns a string in which the elements of the sequence have been joined by a str separator. Using join() we add the characters of the tuple and convert it into a string.


1 Answers

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}'
like image 165
L3viathan Avatar answered Sep 19 '22 03:09

L3viathan