Python Forum

Full Version: Can't figure this one out
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm brand new to programming, busy practicing some coding. What am I doing wrong here? Confused 

>>>farm_equipment = ["jd r4038", "jd 9620", "jd 9630", "jd 4455", "jd 6140d", "jd 9860", "jd 9870", "jd seeder"]
>>>message_c = "\nList of current equipment: "
>>>print(message_c + farm_equipment)
I'm getting the following error:

Error:
Traceback (most recent call last):   File "every_function_c3.py", line 17, in <module>     print(message_c + farm_equipment) TypeError: must be str, not list
Of course there are other lines of code, they all execute perfectly, but I'm not sure if any of those have an impact on these particular lines.

Thanks in advance for any help!
(May-14-2017, 07:39 PM)Stefython Wrote: [ -> ]I'm brand new to programming, busy practicing some coding. What am I doing wrong here? Confused 

>>>farm_equipment = ["jd r4038", "jd 9620", "jd 9630", "jd 4455", "jd 6140d", "jd 9860", "jd 9870", "jd seeder"]
>>>message_c = "\nList of current equipment: "
>>>print(message_c + farm_equipment)


I'm getting the following error:

Traceback (most recent call last):
  File "every_function_c3.py", line 17, in <module>
    print(message_c + farm_equipment)
TypeError: must be str, not list

You are trying to add incompatible types - string and list. You can print either directly - though in case of list it may look strange to you.

In order to concatenate, you have to convert list to string - one of the usual methods is to join it
    print(message_c + ', '.join(farm_equipment))
Farm equipment is a list of strings. You cant concatenate a string with a list.
Hello!
The + sign is string concatenation. But string concatenation, not string + list. They are different types.
Try:
print('{}{}'.format(message_c, farm_equipment))

It's the simplest way
Thanks everybody!
Your answers helped allot.

I'm just still a bit confused. In earlier lines of code I used the same type of code as described above and it would execute without any error:

message = "\nMy favorite machine is the "

print(message + farm_equipment[0].upper())
The result:

Output:
My favorite machine is the JD R4038
Is this because I'm specifying an element from the list, which is a string and is thus allowed?
(May-14-2017, 08:59 PM)Stefython Wrote: [ -> ]s this because I'm specifying an element from the list, which is a string and is thus allowed?
The fact that it worked should be a good indictor that its allowed.what do you want it to do?
Well, you could use join to get some normal looks for the print function

print('{}{}'.format(message_c, ', '.join(farm_equipment)))