开发者

Cannot concatenate 'str' and 'list' objects

开发者 https://www.devze.com 2023-01-06 07:24 出处:网络
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.

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 Admi开发者_如何学CnistrativeAll.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


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]


dbname = [i+"All.dbf" for i in group]


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.


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"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号