tags:

views:

1696

answers:

3

What does : TypeError: cannot concatenate 'str' and 'list' objects mean??

I'm getting this error.. and I know it's saying I'm trying to add a string and a number maybe? but I'm not sure how to fix it

Here's part of the code:

for j in ('90.','52.62263.','26.5651.','10.8123.'):
    if j == '90.':
        z = ('0.')
    elif j == '52.62263.':
        z = ('0.', '72.', '144.', '216.', '288.')

    for k in z:
        exepath = os.path.join(exe file location here)
        exepath = '"' + os.path.normpath(exepath) + '"'
        cmd = [exepath + '-j' + str(j) + '-n' + str(z)]

        process=Popen('echo ' + cmd, shell=True, stderr=STDOUT )
        print process

Sorry thought I posted it

+2  A: 

string objects can only be concatenated with other strings. Python is a strongly-typed language. It will not coerce types for you.

you can do:

'a' + '1'

but not:

'a' + 1

in your case, you are trying to concat a string and a list. this won't work. you can append the item to the list though, if that is your desired result:

my_list.append('a')
Corey Goldberg
+3  A: 

I'm not sure you're aware that cmd is a one-element list, and not a string.

Changing that line to the below would construct a string, and the rest of your code will work:

# Just removing the square brackets
cmd = exepath + '-j' + str(j) + '-n' + str(z)

I assume you used brackets just to group the operations. That's not necessary if everything is on one line. If you wanted to break it up over two lines, you should use parentheses, not brackets:

# This returns a one-element list
cmd = [exepath + '-j' + str(j) + 
       '-n' + str(z)]

# This returns a string
cmd = (exepath + '-j' + str(j) + 
       '-n' + str(z))

Anything between square brackets in python is always a list. Expressions between parentheses are evaluated as normal, unless there is a comma in the expression, in which case the parentheses act as a tuple constructor:

# This is a string
str = ("I'm a string")

# This is a tuple
tup = ("I'm a string","me too")

# This is also a (one-element) tuple
tup = ("I'm a string",)
Triptych
This code seems to loop back more than it should no?
Tyler
@Tyler - not sure what you're talking about. My code contains no loops.
Triptych
referring to his. seems to almost randomly loop back to 90 when it shouldn't.
Tyler
+1  A: 

There is ANOTHER problem in the OP's code:

z = ('0.') then later for k in z:

The parentheses in the first statement will be ignored, leading to the second statement binding k first to '0' and then '.' ... looks like z = ('0.', ) was intended.

John Machin