Anjali
Anjali

Reputation: 506

Tuple and List to formatted string in python

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

Answers (5)

José Garcia
José Garcia

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

AGN Gazer
AGN Gazer

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

CaptainMeow
CaptainMeow

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

Harshit Garg
Harshit Garg

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

Chris
Chris

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

Related Questions