python - 如何区分字符串和其他Iterables?

标签 python string iterable

我试图通过传递一个参数来重载我的函数,该参数可能是一个字符串或字符串列表。最终得到字符串列表的最简单方法是什么?

>>> foo
'bar'
>>> bar
['foo', 'bar']

def myfunc(arg):
    listarg = list()
    listarg.extend(arg)
    print listarg

>>> myfunc(bar)
['foo', 'bar']
>>> myfunc(foo)
['b', 'a', 'r']

当我通过 foo 时,我想看到 ['bar']

我曾尝试过使用 isinstance(arg, str) 或 isinstance(arg, unicode)isinstance(arg, collections.Iterable) 但我并不兴奋关于它们,因为后者不起作用,而前者,我不能只是加入一个列表或其他东西 - 我虽然 str 会这样做,但后来 unicode 来了一直以来,我现在担心可能会有更多的东西可供测试。

最佳答案

在 Python 2 中,strunicode 均派生自 basestring

唉,在Python 3中,没有这样的公共(public)父类。在这里您应该测试 strbytes


def myfunc(arg):
    listarg = arg if not isinstance(arg, basestring) else [arg]
    print listarg

>>> myfunc(bar)
['foo', 'bar']
>>> myfunc(foo)
['bar']

>>> print sys.version
2.7.2 (default, Jun 20 2012, 16:23:33) 

关于python - 如何区分字符串和其他Iterables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12930082/

相关文章:

python - 我想从列表中添加以下内容,但结果只是 concatinates

c# - 不带空格的字符串长度 (C#)

Python 在某一点切割字符串

python - "Int"对象不可迭代

python - 使用相同的表单来创建和更新但不同的验证逻辑

python - Python如何查找模块和方法

python - 在python中获取正在运行的显示服务器的名称

javascript - 在 java 脚本 websockets 中获取第一个单词

Python -TypeError : 'int' object is not iterable

python - 为什么在 iterable 上调用 list() 会改变它?