Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting lists of tuples to strings Python

I've written a function in python that returns a list, for example

[(1,1),(2,2),(3,3)] 

But i want the output as a string so i can replace the comma with another char so the output would be

'1@1' '2@2' '3@3' 

Any easy way around this?:) Thanks for any tips in advance

like image 373
user457142 Avatar asked Nov 26 '10 10:11

user457142


2 Answers

This looks like a list of tuples, where each tuple has two elements.

' '.join(['%d@%d' % (t[0],t[1]) for t in l])

Which can of course be simplified to:

' '.join(['%d@%d' % t for t in l])

Or even:

' '.join(map(lambda t: '%d@%d' % t, l))

Where l is your original list. This generates 'number@number' pairs for each tuple in the list. These pairs are then joined with spaces (' ').

The join syntax looked a little weird to me when I first started woking with Python, but the documentation was a huge help.

like image 130
Johnsyweb Avatar answered Oct 02 '22 18:10

Johnsyweb


You could convert the tuples to strings by using the % operator with a list comprehension or generator expression, e.g.

ll = [(1,1), (2,2), (3,3)]
['%d@%d' % aa for aa in ll]

This would return a list of strings like:

['1@1', '2@2', '3@3']

You can concatenate the resulting list of strings together for output. This article describes half a dozen different approaches with benchmarks and analysis of their relative merits.

like image 44
ConcernedOfTunbridgeWells Avatar answered Oct 02 '22 20:10

ConcernedOfTunbridgeWells