python list转换字符串报错TypeError: sequence item 0: expected str instance, int found

 

python list转换字符串报错TypeError: sequence item 0: expected str instance, int found

场景:将列表转化为指定分隔符的字符串,列表当中有数字时会报如上错误。

 

user.txt:
alex:202cb962ac59075b964b07152d234b70:1234:0
tom:202cb962ac59075b964b07152d234b70:2234:0
test01:202cb962ac59075b964b07152d234b70::0

d_user内容如下: {'alex': ['alex', '202cb962ac59075b964b07152d234b70', '1234', '0'], 'tom': ['tom', '202cb962ac59075b964b07152d234b70', '2234', '0'], 'test01': ['test01', '202cb962ac59075b964b07152d234b70', '', '0']}

>>> l1 = ['alex', '202cb962ac59075b964b07152d234b70', '1234', 0]
'0'

>>> ':'.join(l1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 3: expected str instance, int found

解决办法:

>>> ':'.join('%s' %i for i in l1)
'alex:202cb962ac59075b964b07152d234b70:1234:0'

  

def dolock(username):
    file_content = ""
    d_user[username][3] = 1
    for k in d_user:
        file_content += ':'.join(d_user[k]) + '\n'
    with open(user_file,'r+') as ufile:
        ufile.write(file_content)

 

def dolock(username):
    file_content = ""
    d_user[username][3] = 1
    for k in d_user:
        file_content += ':'.join('%s' %i for i in d_user[k]) + '\n'
    with open(user_file,'r+') as ufile:
        ufile.write(file_content)

  

posted @ 2018-10-07 23:31  念宗  阅读(1372)  评论(0编辑  收藏  举报