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}'
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.
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.
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.
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)
>>> jointuple((1,('2,3',4)))
'1;{2,3;4}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With