0

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!

5 Answers 5

6

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) + ')'
Sign up to request clarification or add additional context in comments.

Comments

2

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)'
>>> 

2 Comments

Not backwards... It's the same order. You just have a 2nd format outside... damn.
Lol. Don't be to hard on your-self ;)
0

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.

Comments

0

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)'

Comments

-1

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.

2 Comments

Your method will not give the other brackets.
i know, it can be easily added, i was showing the 'method' of doing the task with a nicer 'for' loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.