Reputation: 171
I am trying to learn python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere
The task is Think of your favourite mode of transportation and make a list that stores several examples Use your list to print a series of statements about these items
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
print("I like the "+cars[0]+" ...")
I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received The error I get is
TypeError: can only concatenate str (not "list") to str**
Upvotes: 15
Views: 133737
Reputation: 41
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', str(new_dinner))
#Try turning the list into a strang only
Upvotes: 4
Reputation: 573
Here you are the answer :
cars = (['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
print("I like the "+cars[0][0]+" ...")
What we have done here is calling the list first and then calling the first item in the list. since you are storing your data in a tuple, this is your solution.
Upvotes: 0
Reputation: 4888
You can do like
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', *new_dinner)
Upvotes: 0
Reputation: 119
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', new_dinner)
use comma ,
instead of plus +
If you use plus sign +
in print ('this is old friend' + new_dinner)
statement you will get error.
Upvotes: 10
Reputation: 52
This is one of the possibilities you can use to get the result needed.
It learns you to import, use the format method and store datatypes in variables and also how to convert different datatypes into the string datatype!
But the main thing you have to do is convert the list or your wished index into a string. By using str(----)
function. But the problem is that you've created 4 lists, you should only have one!
from pprint import pprint
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
Word = str(cars[0])
pprint("I like the {0} ...".format(Word))
Upvotes: 3
Reputation: 571
First, create a list (not tuple of lists) of strings and then you can access first element (string) of list.
cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
print("I like the "+cars[0]+" ...")
The above code outputs: I like the rav4 ...
Upvotes: 1
Reputation: 777
Your first line actually produces a tuple of lists, hence cars[0]
is a list.
If you print cars
you'll see that it looks like this:
(['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
Get rid of all the square brackets in between and you'll have a single list that you can index into.
Upvotes: 5