string – Python cant convert list object to str error

string – Python cant convert list object to str error

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
print(Here is the whole thing :  + str(letters))

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

string – Python cant convert list object to str error

In addition to the str(letters) method, you can just pass the list as an independent parameter to print(). From the doc string:

>>> print(print.__doc__)
print(value, ..., sep= , end=n, file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.

So multiple values can be passed to print() which will print them in sequence, separated by the value of sep ( by default):

>>> print(Here is the whole thing :, letters)
Here is the whole thing : [a, b, c, d, e]
>>> print(Here is the whole thing :, letters, sep=)   # strictly your output without spaces
Here is the whole thing :[a, b, c, d, e]

Or you can use string formatting:

>>> letters = [a, b, c, d, e]
>>> print(Here is the whole thing : {}.format(letters))
Here is the whole thing : [a, b, c, d, e]

Or string interpolation:

>>> print(Here is the whole thing : %s % letters)
Here is the whole thing : [a, b, c, d, e]

These methods are generally preferred over string concatenation with the + operator, although its mostly a matter of personal taste.

Leave a Reply

Your email address will not be published. Required fields are marked *