Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cant convert 'list' object to str error [closed]

I am using the latest Python 3

letters = ['a', 'b', 'c', 'd', 'e']
letters[:3]
print((letters)[:3])
letters[3:]
print((letters)[3:])
print("Here is the whole thing :" + letters)

Error:

Traceback (most recent call last):
  File "C:/Users/Computer/Desktop/Testing.py", line 6, in <module>
    print("Here is the whole thing :" + letters)
TypeError: Can't convert 'list' object to str implicitly

When fixing, please explain how it works :) i dont want to just copy a fixed line

like image 423
Excetera Avatar asked Sep 14 '14 13:09

Excetera


People also ask

How do you convert a list object to a String in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

What Cannot be converted to String in Python?

All type can be converted in String in python using str.

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .

Can we convert list to object?

A list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list);


2 Answers

As it currently stands, you are trying to concatenate a string with a list in your final print statement, which will throw TypeError.

Instead, alter your last print statement to one of the following:

print("Here is the whole thing :" + ' '.join(letters)) #create a string from elements
print("Here is the whole thing :" + str(letters)) #cast list to string
like image 181
Anshul Goyal Avatar answered Oct 07 '22 08:10

Anshul Goyal


print("Here is the whole thing : " + str(letters))

You have to cast your List-object to String first.

like image 21
Leistungsabfall Avatar answered Oct 07 '22 08:10

Leistungsabfall