0

Why this code not joining the 'pq' in the last string of the list? How can I solve this problem?

a = ['abc', 'xyz', 'lmn'] print ('pq '.join(a)) Output: abcpq xyzpq lmn

9th Jan 2020, 5:45 PM
Ashutosh R. Yadav
Ashutosh R. Yadav - avatar
6 Respuestas
+ 2
If you want to add pq to the end just do + 'pq' after the join.
9th Jan 2020, 6:07 PM
Pie
Pie - avatar
+ 5
乡Ashutosh°^°Kumar乡 what Pie said will work. But in this case, what is the purpose of using join at all? Just loop throught it and add it: result = "" for i in a: result += a+"pq"
9th Jan 2020, 6:09 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 3
Because join merhos attaches the elements of a list using a specific string, and doesn't add to the end of each element. Let say y.ou have three boxes in real life, and wanted to attach them □ □ □ You will use the glue (represented by |) only two times, between the boxes only. Otherwise, there will be an ugly looking glue on the right side, that is sticky. □|□|□ looks better than □|□|□|, and the last glue has no meaning. Same goes here, only attaches the elements together.
9th Jan 2020, 6:00 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Aymane Boukrouh [INACTIVE] result=' '.join([x+'pq' for x in a]) would also work as a one liner.
9th Jan 2020, 6:16 PM
Pie
Pie - avatar
+ 1
Aymane Boukrouh [INACTIVE] Then how can I get my desired out? I wanted to add 'pq' in the end of all the strings in the list a.
9th Jan 2020, 6:03 PM
Ashutosh R. Yadav
Ashutosh R. Yadav - avatar
+ 1
Thank you guys Pie and Aymane Boukrouh [INACTIVE] It helped me. Keep it up.. Cheers!!!
9th Jan 2020, 6:18 PM
Ashutosh R. Yadav
Ashutosh R. Yadav - avatar