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
This looks like a list
of tuple
s, 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With