tags:

views:

112

answers:

5

Hello - I'm getting a TypeError: cannot concatenate 'str' and 'list' objects.

I'm trying to pass an object from a list to create a new variable by concatenating it with another variable.

Example: I want to take the value from the group list and concatenate it with "All.dbf" so it will do something with that file for each value in my list. If working properly, it would set the value for dbname equal to AdministrativeAll.dbf, CadastralAll.dbf and PlanimetericAll.dbf respectively each time it runs through but I am getting the 'str' and 'list' error....

group = ['Administrative', 'Cadastral', 'Planimetric']

for i in group:
    dbname = i + "All.dbf"

    blah, blah, blah....

I suppose I could add the "All.dbf" onto the values in the group list but thought there must be a better way to process this with a function or something that I don't know about....any thoughts??

Cheers

+4  A: 

I suppose I could add the "All.dbf" onto the values in the group list but thought there must be a better way to process this with a function or something that I don't know about...

You could use a list comprehension:

group = [x + 'All.dbf' for x in group]
Mark Byers
Very slick - I like it - thanks Mark!!
Jay
+1  A: 
dbname = [i+"All.dbf" for i in group]
iamgopal
A: 

you will need to go though each item in the list and concatenate the two. A for each loop is your best bet. I'm not as familiar with python, so you might have to iterate over the list.

A: 

Running this in 2.6.5:

group = ['Administrative', 'Cadastral', 'Planimetric']
for i in group:
    dbname = i + "All.dbf"
    print 'Concat', dbname

Gives the following output:

Concat AdministrativeAll.dbf
Concat CadastralAll.dbf
Concat PlanimetricAll.dbf

Worst case you can iterate through a range that is the length of the list, then do group[i] + "string to concatenate"

thegrinner
A: 

I too can see nothing wrong with your original code, and it works fine for me pasted into a python 2.6 interpreter.

Gopal's solution is neater and more "pythonic" though

AlanL