开发者

Python list and type error

I've code this code in Python:

if type(data).__name__=='list':
                print type(data).__name__
                print ",".join(data)

And it give me this error:

    print ",".join(data)
exceptions.TypeError: sequence item 0: expected string, list found

Ho开发者_运维知识库w's that possible?!?

Thanks in advance for anyhelp.


You appear to have a list of lists. Try:

",".join(str(x) for x in data)


str.join() can only join a sequence of strings. Obviously your list contains an item that itself is a list again.

Furthermore, if you really need to check for the type of an object, a better way to do it is

if isinstance(data, list):
    ...


The first element of data is a list. It must be a string in order for str.join() to work as shown. In fact, all elements must.


Don't explicitly check for types. If you do need to, use isinstance.

The error is appearing because of the contents of data rather than its type. It needs to be a list of strings for the str.join method to work on it.


The first element of your list is also a list, not a string.

Also you don't have to do type(data).__name__=='list' - just type(data) is list

Even better - just check with isinstance since you don't really care about a specific type in most cases.


join expects an iterable of strings. What seems to happen in your case is that the first element of your list is another list. This is what's causing the error.

As an aside, the if type(data).__name__=='list': ... is as un-Pythonic as code gets.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜