TypeError用于解析类型

2024-04-24 09:44:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在函数中找到一个bug:

def buggy_join(input, sep=","):
   return sep.join(input)

当我试图调用函数时使用:

buggy_join(range(6))

它显示类型错误,说明找到了预期的字符串int。 我该怎么解决是的。是的join函数只适用于basestring类型??你知道吗

input = list(itertools.chain(*enumerate("abc")))
buggy_join(input, ".")

即使是上述调用,它也会导致相同的错误。你知道吗


Tags: 函数字符串类型inputreturndef错误range
2条回答

鉴于您已经正确地解决了问题,这里有一个解决方案:

def not_buggy_join(input, sep=","):
    return sep.join(map(str, input))

the documentationmap(function, iterable)

Apply function to every item of iterable and return a list of the results.

在本例中,它将所有内容转换为str。用你自己的例子:

>>> not_buggy_join(itertools.chain(*enumerate("abc")))
'0,a,1,b,2,c'

相关问题 更多 >