PYTHON错误之TypeError: sequence item 0: expected str instance, int found的原因和解决方法

前几天写代码的时候,任务是把传入的参数用"_"隔开,然后追加到文件中

直接上代码

def operate(file_path, *args):
    f = open(file_path, mode="a", encoding="utf-8")
    s = ""
    s = '_'.join(args)
    f.write(s)
    f.flush()
    f.close()
operate("hhhh.txt", 123, 456, 789)

本来题意是接收字符串,但是我手误写了数字,然后报错了

错误提示是TypeError: sequence item 0: expected str instance, int found,大概意思就是期待字符串类型,但是我给了数字类型

然后找文档,下面是原文

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

其实join函数就是字符串的函数,参数和插入的都要是字符串

所以:

将s = '_'.join(args)变成

s = '_'.join(str(args).strip())

就可以解决了!

扫描二维码关注公众号,回复: 4536368 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_38115310/article/details/84899569