A
A
Anton2018-07-19 15:28:45
Python
Anton, 2018-07-19 15:28:45

How to convert a tuple with multiple elements into one string?

Let's say there is a tuple and two elements are written in it:
tuple= ((a1, a2, a3), (b1, b2, b3))
How to convert all elements of the tuple into one line, for example, I know one way, this is through for:

for numFor in range(0, len(tuple)):
        list = list + str(tuple[numFor])

Can you please tell me if there is an easier way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tema_sun, 2018-07-19
@8toni8

Well, like this for example:
Or you can use itertools:

import itertools
flatten = [str(item) for item in itertools.chain(*tuple)]

And then do a join:
"".join(flatten)

S
Sergey Sokolov, 2018-07-19
@sergiks

str.join() joins the elements of the list through the specified string;
map() applies the specified function to each element of the list.

t = (('a1', 'a2', 'a3'), ('b1', 'b2', 'b3'))

';'.join(map(','.join,t)) # 'a1,a2,a3;b1,b2,b3'

Instead of ;and, ,you can specify other separators, incl. empty line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question