如何找出一个Python对象是一个string?
我怎样才能检查一个Python对象是一个string(无论是普通的或Unicode)?
Python 2
使用isinstance(obj, basestring)来testingobj 。 
文档
检查一个对象是否是一个stringtypes的子类的stringtypes:
 isinstance(o, basestring) 
 因为str和unicode都是basestring子类。 
 要检查o的types是不是str : 
 type(o) is str 
 检查o是str还是str任何子类的一个实例: 
 isinstance(o, str) 
 上面也适用于Unicodestring,如果你用unicodereplacestr 。 
但是,您可能根本不需要进行明确的types检查。 “鸭子打字”可能适合您的需求。 请参阅http://docs.python.org/glossary.html#term-duck-typing 。
另请参见在python中检查types的规范方法是什么?
Python 3
 在Python 3.x中, basestring不再可用,因为str是唯一的stringtypes(具有Python 2.x的unicode的语义)。 
所以在Python 3.x中的检查只是:
 isinstance(obj_to_test, str) 
 这遵循官方2to3转换工具的修复 :将basestring转换为str 。 
Python 2和3
(横尺寸)
 如果你想检查Python版本(2.x和3.x),请使用six ( PyPI )和它的string_types属性: 
 import six if isinstance(obj, six.string_types): print('obj is a string!') 
 在six (一个非常轻量级的单文件模块)内,它只是这样做的: 
 import sys PY3 = sys.version_info[0] == 3 if PY3: string_types = str, else: string_types = basestring, 
为了检查你的variables是否可以这样做:
 s='Hello World' if isinstance(s,str): #do something here, 
isistance的输出会给你一个布尔型的True或False值,所以你可以相应地进行调整。 您可以通过以下方式检查您的值的预期首字母缩略词:type(s)这将返回您键入'str',以便您可以在isistance函数中使用它。
我发现这个更加pythonic:
 if type(aObject) is str: #do your stuff here pass 
因为types对象是单例,可以用来做比较
像其他人提到的那样,我可能会用鸭子式的方式来处理这个问题。 我怎么知道一个string真的是一个string? 很明显,通过将其转换为string!
 def myfunc(word): word = unicode(word) ... 
 如果arg已经是string或unicodetypes,则real_word将保持其值不变。 如果传递的对象实现了一个__unicode__方法,该方法用于获取其unicode表示。 如果传递的对象不能用作string,则unicode内build会引发exception。 
如果想远离明确的types检查(并且有很好的理由远离它),可能最需要检查的string协议中最安全的部分是:
 str(maybe_string) == maybe_string 
它不会遍历一个迭代器或迭代器,它不会调用一个string列表,而是正确地检测一个string作为一个string。
 当然有缺点。 例如, str(maybe_string)可能是一个沉重的计算。 像往常一样,答案是依赖的 。 
 isinstance(your_object, basestring) 
如果你的对象确实是一个stringtypes的话就会是True的。 'str'是保留字。
我的道歉,正确的答案是使用'basestring'而不是'str'按顺序包含unicodestring – 正如其他响应者之一所述。
你可以通过连接一个空string来testing它:
 def is_string(s): try: s += '' except: return False return True 
编辑 :
纠正我的答案后,指出这与列表失败
 def is_string(s): return isinstance(s, basestring) 
 今天晚上,我遇到了一个情况,我想我将不得不去检查strtypes,但事实certificate我没有。 
我的解决问题的方法很可能会在很多情况下工作,所以我在下面提供它,以防其他人阅读这个问题感兴趣(仅适用于Python 3)。
 # NOTE: fields is an object that COULD be any number of things, including: # - a single string-like object # - a string-like object that needs to be converted to a sequence of # string-like objects at some separator, sep # - a sequence of string-like objects def getfields(*fields, sep=' ', validator=lambda f: True): '''Take a field sequence definition and yield from a validated field sequence. Accepts a string, a string with separators, or a sequence of strings''' if fields: try: # single unpack in the case of a single argument fieldseq, = fields try: # convert to string sequence if string fieldseq = fieldseq.split(sep) except AttributeError: # not a string; assume other iterable pass except ValueError: # not a single argument and not a string fieldseq = fields invalid_fields = [field for field in fieldseq if not validator(field)] if invalid_fields: raise ValueError('One or more field names is invalid:\n' '{!r}'.format(invalid_fields)) else: raise ValueError('No fields were provided') try: yield from fieldseq except TypeError as e: raise ValueError('Single field argument must be a string' 'or an interable') from e 
一些testing:
 from . import getfields def test_getfields_novalidation(): result = ['a', 'b'] assert list(getfields('a b')) = result assert list(getfields('a,b', sep=',')) = result assert list(getfields('a', 'b')) = result assert list(getfields(['a', 'b'])) = result 
对于喜欢使用Python 2.x和3.x的string的鸭子打字方法:
 def is_string(obj): try: obj + '' return True except TypeError: return False 
 在切换到isinstance方法之前, wisefish与duck-typing很接近,除了+=对列表的含义与+不同之外。 
 if type(varA) == str or type(varB) == str: print 'string involved' 
来自EDX – 在线课程MITx:6.00.1x介绍计算机科学和使用Python进行编程