[英]Tuple and List to formatted string in python
In Python3.4 I have a tuple 在Python3.4中,我有一个元组
t = ('A', 'B', 'C')
and a list 和一个清单
l = ['P', 'Q', 'R']
and I need to convert the tuple to a string formatted as "(#A;#B;#C)"
and the list to a string formatted as "(@P; @Q; @R)"
. 并且我需要将元组转换为格式为
"(#A;#B;#C)"
的字符串,并将列表转换为格式为"(@P; @Q; @R)"
的字符串。 The obvious way is to traverse using a for loop and string manipulation. 显而易见的方法是使用for循环和字符串操作进行遍历。
Is there a way to do it without running the loop? 有没有一种方法可以不运行循环?
Thanks! 谢谢!
If you really insist on your format and no for loops, then probably try something like the following: 如果您确实坚持使用格式而不使用for循环,则可以尝试以下操作:
l_result = '(@' + '; @'.join(l) + ')'
t_result = '(#' + ';#'.join(t) + ')'
Why not use a loop? 为什么不使用循环? This can be done very simply using a comprehension:
这可以使用理解非常简单地完成:
>>> t = ('A', 'B', 'C')
>>> '({})'.format(';'.join('#{}'.format(s) for s in t))
'(#A;#B;#C)'
>>>
>>> l = ['P', 'Q', 'R']
>>> '({})'.format('; '.join('@{}'.format(s) for s in l))
'(@P; @Q; @R)'
>>>
If not using a loop is the case, another approach can be to convert them to string and use replace method of string, as follows 如果不是使用循环,则另一种方法可以是将它们转换为字符串并使用字符串的替换方法,如下所示
str(t).replace("', '", ";#").replace("('", "(#").replace("')", ")")
str(l).replace("', '", '; @').replace("['", "(@").replace("']", ")")
If there are only three elements, you can replace them individually as well. 如果只有三个元素,则也可以单独替换它们。
No explicit loops, not even as list comprehension: 没有显式循环,甚至没有列表理解:
>>> t = ('A', 'B', 'C')
>>> l = ['P', 'Q', 'R']
>>> '(' + (len(t) * '#%s;')[:-1] % t + ')'
'(#A;#B;#C)'
>>> '(' + (len(l) * '@%s; ')[:-2] % tuple(l) + ')'
'(@P; @Q; @R)'
i dont know why you dont want to use the for loop, but you can do it using list comprehension, you will use the for loop, but in a prettier way 我不知道为什么您不想使用for循环,但是您可以使用列表理解来实现,您将使用for循环,但是方法更漂亮
l = ['P', 'Q', 'R']
new = '('+'; '.join(['@'+i for i in l])+')'
print(new)
(@P; @Q; @R)
you could do the same for the tuple. 您可以对元组执行相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.