[英]What is the Pythonic Way of Differentiating Between a String and a List?
For my program I have a lot of places where an object can be either a string or a list containing strings and other similar lists. 对于我的程序,我有很多地方,对象可以是字符串或包含字符串和其他类似列表的列表。 These are generally read from a JSON file. 这些通常是从JSON文件中读取的。 They both need to be treated differently. 他们都需要区别对待。 Right now, I am just using isinstance, but that does not feel like the most pythonic way of doing it, so does anyone have a better way of doing it? 现在,我只是使用isinstance,但这并不是最狡猾的方式,所以有没有人有更好的方法呢?
No need to import modules, isinstance()
, str
and unicode
(versions before 3 -- there's no unicode
in 3!) will do the job for you. 无需导入模块, isinstance()
, str
和unicode
(3之前的版本 - 3中没有unicode
!)将为您完成工作。
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(u'', (str, unicode))
True
>>> isinstance('', (str, unicode))
True
>>> isinstance([], (str, unicode))
False
>>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']):
... print type(value)
...
<type 'str'>
<type 'unicode'>
<type 'list'>
Python 3.2 (r32:88445, May 29 2011, 08:00:24)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance('☃ ', str)
True
>>> isinstance([], str)
False
>>> for value in ('snowman', '☃ ', ['snowman', '☃ ']):
... print(type(value))
...
<class 'str'>
<class 'str'>
<class 'list'>
Object type comparisons should always use
isinstance()
instead of comparing types directly. 对象类型比较应始终使用isinstance()
而不是直接比较类型。
Since Python3 no longer has unicode
or basestring
, in this case ( where you are expecting either a list or a string) it's better to test against list
由于Python3不再具有unicode
或basestring
,在这种情况下(你期望列表或字符串),最好对list
进行测试
if isinstance(thing, list):
# treat as list
else:
# treat as str/unicode
as that is compatible with both Python2 and Python3 因为它兼容Python2和Python3
Using isinstance
: 使用isinstance
:
On Python>=2.3 a string may be a str
or unicode
type. 在Python> = 2.3上,字符串可以是str
或unicode
类型。 To check both cases: 检查两种情况:
if isinstance(a,basestring): # same as isinstance(obj, (str, unicode))
print "Object is a string"
From Python 3 only one string type exists, so instead of basestring
you should use str
: 从Python 3只存在一个字符串类型,因此你应该使用str
来代替basestring
:
if isinstance(a,str):
print "Object is a string"
Another method, using the practice of "It's better to ask forgiveness than permission," duck-typing being generally preferred in Python, you could try to do what you want first, eg: 另一种方法,使用“请求宽恕而非许可更好”的做法,在Python中通常首选鸭子打字,你可以尝试先做你想做的事,例如:
try:
value = v.split(',')[0]
except AttributeError: # 'list' objects have no split() method
value = v[0]
As I like to keep things simple, here is the shortest form that is compatible with both 2.x and 3.x: 因为我喜欢保持简单,这里是与2.x和3.x兼容的最短形式:
# trick for py2/3 compatibility
if 'basestring' not in globals():
basestring = str
v = "xx"
if isinstance(v, basestring):
print("is string")
You can use types module: 您可以使用类型模块:
import types
if type(ls) == types.ListType:
#your code for list objects here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.