TypeError: can only concatenate str (not "list") to str in Python

Dung Do Tien Sep 19 2021 9

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have some like code, I created an array of cars and I want to get first item of that array, I access by index. Function as below:

 cars = ['Camry'], ['Lambogini'], ['Mazda CX'], ['Land Rover'] 

print("I choose the " + cars[0] + " if I have enough money to buy it.")

But I get an exception TypeError: can only concatenate str (not "list") to str when I run code above.

 Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print("I choose the " + cars[0] + " if I have enough money to buy it.")
TypeError: can only concatenate str (not "list") to str

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 2 answer(s) found.
  • R

    Rahul Bagale Sep 19 2021

    You need to convert cars[0] to string by using str() method. See like this:

     cars = ['Camry'], ['Lambogini'], ['Mazda CX'], ['Land Rover'] 
    
    print("I choose the " + str(cars[0]) + " if I have enough money to buy it.")

    #Output

     I choose the ['Camry'] if I have enough money to buy it. 
  • k

    khati Sep 19 2021

    You created a typle of list so you can not access directly by index, you can use str() method to help convert tuply to string.

     print("I choose the " + str(cars[0]) + " .....")

    Or you can declare your array is string only, not typle of list. For an example:

     cars = ['Camry', 'Lambogini', 'Mazda CX', 'Land Rover'] 
    
    print("I choose the " + cars[0] + " if I have enough money to buy it.")

    And output:

     I choose the Camry if I have enough money to buy it.

    I hope it clear for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close