8

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}'
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
PhilHibbs
  • 859
  • 1
  • 13
  • 30
  • What do you mean by select the parentheses? Show us expected output. Looks like you can create a recursive function. – Anton vBR Dec 13 '17 at 14:47
  • 4
    I also thought the duplicate was wrong. but that happens sometimes. – Anton vBR Dec 13 '17 at 14:54
  • 2
    Yeah, this has nothing to do with flattening... an odd dupe. – glibdud Dec 13 '17 at 14:55
  • If the string is the only problem and if you're sure that patterns such as `'('`, `'('` or `', '` couldn't be encountered in string conversions of atomic elements, you could also use `replace()` : `yourstring.replace('(', ';').replace(')', ';').replace(', ', ';')`. – vmonteco Dec 13 '17 at 14:58
  • I can't use `replace` - the reason I want to specify the separator is in case a comma appears in an element. – PhilHibbs Dec 13 '17 at 15:01
  • 2
    @COLDSPEED this is an absolutely incorrect flagging of a question. – AGN Gazer Dec 13 '17 at 15:02
  • 1
    Define a function such as `f = lambda t: '(' + ','.join(map(str, t)) +')' if hasattr(t, '__iter__') else str(t)` and map `f` to your sequence: `';'.join(map(f, a))` where `a=(1,(2,3))`. Since this question was closed, I cannot provide a more complete answer on how to handle parenthesis. – AGN Gazer Dec 13 '17 at 15:05

1 Answers1

3

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}'
L3viathan
  • 26,748
  • 2
  • 58
  • 81
  • 1
    You might want to add parameters for the braces and separator: `def jointuple(tpl, sep=';', lbr='{', rbr='}')`, unless I misunderstood what OP means by selecting the braces. +1 regardless. – Mad Physicist Dec 13 '17 at 16:21