首页 文章

如何确定Python对象是否为字符串?

提问于
浏览
317

如何检查Python对象是否为字符串(常规或Unicode)?

13 回答

  • 144

    Python 3

    在Python 3.x中, basestring 不再可用,因为 str 是唯一的字符串类型(具有Python 2.x的 unicode 的语义) .

    因此,Python 3.x中的检查只是:

    isinstance(obj_to_test, str)
    

    这是在官方 2to3 转换工具的the fix之后:将 basestring 转换为 str .

  • -1

    如果想要远离显式类型检查(并且有充分的理由远离它),可能要检查的字符串协议中最安全的部分是:

    str(maybe_string) == maybe_string
    

    它赢得了't iterate through an iterable or iterator, it won' t调用字符串列表字符串并且它正确地将stringlike检测为字符串 .

    当然有缺点 . 例如, str(maybe_string) 可能是一个繁重的计算 . 通常,答案取决于它 .

  • 3

    要检查对象 o 是否是字符串类型的子类的字符串类型:

    isinstance(o, basestring)
    

    因为 strunicode 都是 basestring 的子类 .

    要检查 o 的类型是否完全是 str

    type(o) is str
    

    要检查 ostr 的实例还是 str 的任何子类:

    isinstance(o, str)
    

    如果将 str 替换为 unicode ,则上述内容也适用于Unicode字符串 .

    但是,您可能根本不需要进行显式类型检查 . "Duck typing"可能符合您的需求 . 见http://docs.python.org/glossary.html#term-duck-typing .

    另见What’s the canonical way to check for type in python?

  • -4

    您可以通过连接空字符串来测试它:

    def is_string(s):
      try:
        s += ''
      except:
        return False
      return True
    

    Edit

    在评论指出这与列表失败后纠正我的答案

    def is_string(s):
      return isinstance(s, basestring)
    
  • 112
    isinstance(your_object, basestring)
    

    如果您的对象确实是字符串类型,则为True . 'str'是保留字 .

    我的道歉,正确的答案是使用'basestring'而不是'str',以便它包括unicode字符串 - 正如上面其他响应者之一所述 .

  • 1

    Python 2和3

    (交叉兼容)

    如果你想检查不考虑Python版本(2.x vs 3.x),请使用sixPyPI)及其 string_types 属性:

    import six
    
    if isinstance(obj, six.string_types):
        print('obj is a string!')
    

    six (一个非常轻量级的单文件模块)中,它只是做this

    import sys
    PY3 = sys.version_info[0] == 3
    
    if PY3:
        string_types = str
    else:
        string_types = basestring
    
  • 7

    Python 2

    使用 isinstance(obj, basestring) 进行对象测试 obj .

    Docs .

  • 7

    今天晚上我遇到了一个情况,我不得不检查 str 类型,但事实证明我没有 .

    我解决问题的方法可能适用于很多情况,所以我在下面提供它以防其他人阅读这个问题感兴趣(仅限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
    

    一些测试:

    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
    
  • 281

    为了检查你的变量是否适合你:

    s='Hello World'
    if isinstance(s,str):
    #do something here,
    

    isistance的输出将为您提供布尔值True或False值,以便您可以相应地进行调整 . 您可以通过最初使用来检查值的预期首字母缩写:type(s)这将返回键入'str',以便您可以在isistance函数中使用它 .

  • 11

    对于一个很好的鸭子类型的方法,可以使用Python 2.x和3.x:

    def is_string(obj):
        try:
            obj + ''
            return True
        except TypeError:
            return False
    

    wisefish在切换到 isinstance 方法之前与鸭子打字很接近,除了 += 对列表的含义不同于 + .

  • 77

    我发现这个更加pythonic:

    if type(aObject) is str:
        #do your stuff here
        pass
    

    由于类型对象是单例,因此可以使用 is 进行比较

  • 5

    我可能会像其他人提到的那样以鸭子打字的方式处理这个问题 . 我怎么知道字符串真的是一个字符串?好吧,显然通过将其转换为字符串!

    def myfunc(word):
        word = unicode(word)
        ...
    

    如果arg已经是字符串或unicode类型,则real_word将保持其值不被修改 . 如果传递的对象实现 __unicode__ 方法,则用于获取其unicode表示 . 如果传递的对象不能用作字符串,则 unicode builtin会引发异常 .

  • 1
    if type(varA) == str or type(varB) == str:
        print 'string involved'
    

    来自EDX - 在线课程MITx:6.00.1x计算机科学和使用Python编程简介

相关问题