[英]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
: 我还需要处理带逗号的字符串,所以我不能使用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)
>>> jointuple((1,('2,3',4)))
'1;{2,3;4}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.