Python Forum
Regarding concatenation of a list to a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Regarding concatenation of a list to a string (/thread-12304.html)



Regarding concatenation of a list to a string - Kedar - Aug-19-2018

This is the code I wrote initially,

print("Once upon a time, 5 men were walking by the forest")
warriors = ["Kevin", "Casper", "Nick", "Jim", "Napolean"]
print("The names of these men were: " + (warriors))
However, it gives TypeError : can only concatenate str (not "list") to str

So I modified the code this way:

print("Once upon a time, 5 men were walking by the forest")
warriors = ["Kevin", "Casper", "Nick", "Jim", "Napolean"]
print("The names of these men were: " + str(warriors))
And now its working fine, but I don't understand why

It would be great if you could explain this to me.

Thanks


RE: Regarding concatenation of a list to a string - buran - Aug-19-2018

you cannot add objects of different type - str and list.
by the way, it's better to use advanced string formatting methods, rather than convert the list to str and then using +
warriors = ["Kevin", "Casper", "Nick", "Jim", "Napolean"]
print("The names of these men were: {}".format(', '.join(warriors)))
in python 3.6+ you can also use the f-string syntax.
Advanced formatting will be much more handy when it comes to using different types, e.g. numbers


RE: Regarding concatenation of a list to a string - ichabod801 - Aug-19-2018

The reason the second version works is that you converted the list to a string with the str() built-in. So you are adding two strings instead of a list and a string.