Reputation: 506
In Python3.4 I have a tuple
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)"
. The obvious way is to traverse using a for loop and string manipulation.
Is there a way to do it without running the loop?
Thanks!
Upvotes: 0
Views: 183
Reputation: 136
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
l = ['P', 'Q', 'R']
new = '('+'; '.join(['@'+i for i in l])+')'
print(new)
(@P; @Q; @R)
you could do the same for the tuple.
Upvotes: -1
Reputation: 8378
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)'
Upvotes: 0
Reputation: 351
If you really insist on your format and no for loops, then probably try something like the following:
l_result = '(@' + '; @'.join(l) + ')'
t_result = '(#' + ';#'.join(t) + ')'
Upvotes: 6
Reputation: 2259
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.
Upvotes: 0
Reputation: 22953
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)'
>>>
Upvotes: 2