Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create list of substrings of several lines

Imagine I have the following list:

result_lines = ['name1 age1 address1 email1',
                'name2 age2 address2 email2',
                'name3 age3 address3 email3']

I would like to print the following string:

'age1:name1, age2:name2, age3: name3'

Note: no , at the end of the string!

UPDATE: important is not the order age1:name1. it could also be age1:email1:name1.

What I tried so far:

print "".join((l.split(' ')[1], l.split(' ')[0]) for l in result_lines) 

However, I get the following error message:

TypeError: sequence item 0: expected string, tuple found

Thanks for any help.

like image 295
ezdazuzena Avatar asked Dec 05 '25 06:12

ezdazuzena


1 Answers

str.format() is your friend in a situation where you want to present the contents of a list or tuple:

>>> ', '.join(['{1}:{0}'.format(*line.split()) for line in result_lines])
'age1:name1, age2:name2, age3:name3'

To break this down a little, because there's a lot going on in that line...

We start with the simple list comprehension:

>>> [line for line in result_lines]
['name1 age1 address1 email1', 'name2 age2 address2 email2', 'name3 age3 address3 email3']

And split the string into whitespace using str.split() (we only need to split once):

>>> [line.split() for line in result_lines]
[['name1', 'age1', 'address1', 'email1'], ['name2', 'age2', 'address2', 'email2'], ['name3', 'age3', 'address3', 'email3']]

Introduce str.format() and unpack the argument list:

>>> ['{0}:{1}:{2}:{3}'.format(*line.split()) for line in result_lines]
['name1:age1:address1:email1', 'name2:age2:address2:email2', 'name3:age3:address3:email3']

Choose the elements we want:

>>> ['{1}:{0}'.format(*line.split()) for line in result_lines]
['age1:name1', 'age2:name2', 'age3:name3']

(str.)join it all together with ', ':

>>> ', '.join(['{1}:{0}'.format(*line.split()) for line in result_lines])
'age1:name1, age2:name2, age3:name3'

Q.E.D.

like image 194
Johnsyweb Avatar answered Dec 07 '25 00:12

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!