我试图通过传递一个参数来重载我的函数,该参数可能是一个字符串或字符串列表。最终得到字符串列表的最简单方法是什么?
>>> 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 中,str
和 unicode
均派生自 basestring
。
唉,在Python 3中,没有这样的公共(public)父类。在这里您应该测试 str
和 bytes
。
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/