简体   繁体   中英

Error with concatenating list to string in Python

I am trying to pass class element to method. Element is formed dynamically inserting current time in it. Mine class looks something like this:

class MineContact(dict):
    def __init__(self, **kwargs):
        # set your default values
        import time
        curr_time = repr(time.time()).replace('.', '') 
        self['givenName'] = ['name%s' % curr_time[10:]]
        ...

So, I create object of this class and now I want to insert it as method argument:

    contact = MineContact()
    extra_text = "-%d" % (self.iteration)
    new_contact.insert_given_name(contact.givenName + extra_text)

When I run this script, I get this type of error:

TypeError: can only concatenate list (not "str") to list

So, does anyone knows where am I getting it wrong?

givenName seems to be a list. You can append another list like this:

new_contact.insert_given_name(contact.givenName + [extra_text])

contact.givenName is a list, and extra_text is a string. in python you can add string to string, or list to list. you can't add string to list.

if you'd like to add string to a list, use list.append method.

mylist.append(mystr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM