Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis0
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
6 Respostas
+ 2
If you want to add pq to the end just do + 'pq' after the join.
+ 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"
+ 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.
+ 2
Aymane Boukrouh [INACTIVE]
result=' '.join([x+'pq' for x in a])
would also work as a one liner.
+ 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.
+ 1
Thank you guys Pie and Aymane Boukrouh [INACTIVE]
It helped me.
Keep it up.. Cheers!!!