Python Forum
Regarding concatenation of a list to a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regarding concatenation of a list to a string
#1
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
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries i sawtooth500 3 945 Mar-22-2024, 03:08 AM
Last Post: deanhystad
  String concatenation in SQL update statement hammer 3 1,504 Feb-24-2022, 08:00 PM
Last Post: hammer
  f string concatenation problem growSeb 3 2,243 Jun-28-2021, 05:00 AM
Last Post: buran
  Concatenation ?? ridgerunnersjw 1 1,708 Sep-26-2020, 07:29 PM
Last Post: deanhystad
  I converted string to 'list', but it doesn't look like a list! mrapple2020 3 3,239 Apr-07-2019, 02:34 PM
Last Post: mrapple2020
  Combining two strings together (not concatenation) DreamingInsanity 6 3,103 Mar-29-2019, 04:32 PM
Last Post: DreamingInsanity
  Create Alert if string from list appears on other list javalava 1 2,504 Sep-17-2018, 02:44 PM
Last Post: DeaD_EyE
  List of pathlib.Paths Not Ordered As Same List of Same String Filenames QbLearningPython 20 15,335 Nov-16-2017, 04:47 PM
Last Post: QbLearningPython
  Create a new list by comparing values in a list and string DBS 2 3,520 Jan-14-2017, 07:59 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020