【问题标题】:How to check if type of a variable is string?如何检查变量的类型是否为字符串?
【发布时间】:2011-06-18 02:36:30
【问题描述】:

有没有办法检查python中变量的类型是否为string,比如:

isinstance(x,int);

对于整数值?

【问题讨论】:

标签: python string variables types


【解决方案1】:

使用type()isinstance()

我不知道为什么我面前没有一个答案包含这个简单的 type(my_variable) is str 语法,但到目前为止,像这样使用 type() 对我来说似乎是最合乎逻辑和最简单的:

(在 Python3 中测试):

# Option 1: check to see if `my_variable` is of type `str`
type(my_variable) is str

# Option 2: check to see if `my_variable` is of type `str`, including
# being a subclass of type `str` (ie: also see if `my_variable` is any object 
# which inherits from `str` as a parent class)
isinstance(my_variable, str)

Python type() 内置函数文档在这里:https://docs.python.org/3/library/functions.html#type。它部分说明了以下内容。注意关于isinstance()的注释:

class type(object)
class type(name, bases, dict, **kwds)

使用一个参数,返回对象的类型。返回值是一个类型对象,一般与object.__class__返回的对象相同。

建议使用isinstance() 内置函数来测试对象的类型,因为它考虑了子类。

因此,如果您检查的是类对象的类型而不是简单变量,并且您需要考虑子类,那么请改用isinstance()。在此处查看其文档:https://docs.python.org/3/library/functions.html#isinstance

示例代码:

my_str = "hello"
my_int = 7

print(type(my_str) is str)
print(type(my_int) is str)

print()
print(isinstance(my_str, str))
print(isinstance(my_int, str))

输出:

True
False

True
False

【讨论】:

    【解决方案2】:

    总结:

    如果您同时需要 Python2 和 Python3,并且还想包含 unicode,似乎没有一种可移植的方式。我最终使用了这个成语:

    # Near the top of my program
    if sys.version_info[0] >= 3:
        basestring = str
    

    然后任何时候我想测试一个对象,看看它是否是一个字符串:

    if isinstance(obj, basestring):
        ...
    

    坦率地说,我对 Python3 删除了 basestring 以及 types.StringTypes 感到有些震惊。我认为没有理由放弃它们,保留它们中的任何一个都可以解决这个问题。

    【讨论】:

      【解决方案3】:
      >>> thing = 'foo'
      >>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
      True
      

      【讨论】:

      • 在哪种情况下您更喜欢type(thing).__name__ == 'str' 而不是type(thing) == strisinstance(thing, str)?此外,现代版本的 Python 中不存在 unicode
      【解决方案4】:

      在 Python 2.x 中,你会这样做

      isinstance(s, basestring)
      

      basestringstrunicodeabstract superclass。可以用来测试一个对象是str还是unicode的实例。


      在 Python 3.x 中,正确的测试是

      isinstance(s, str)
      

      bytes 类在 Python 3 中不被视为字符串类型。

      【讨论】:

      • @Yarin:不。但这没关系,因为 Python 3.x 根本不兼容 Python 2.x。
      • 我发现 isinstance(s, str) 可与 py27 一起使用,测试于:Python 2.7.5 (default, Aug 25 2013, 00:04:04) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] 在达尔文上。
      • @kakyo:问题是它会错过unicode 对象,这些对象也应该被视为字符串。 strunicode 类型都具有公共基类 basestring,这就是您要检查的内容。
      • @Yarin 如果您要将某些东西从 2.x 移植到 3.x,您可以随时分配 basestring = str
      • @AdamErickson 到底兼容什么?它对与 Python 3 的兼容性没有帮助,因为 Python 3 中没有 unicode。我对 Python 2 和 3 之间的兼容性的建议是使用“six”库。 (在这种情况下特别是isintance(s, six.string_types)
      【解决方案5】:

      你可以这样做:

      var = 1
      if type(var) == int:
         print('your variable is an integer')
      

      或:

      var2 = 'this is variable #2'
      if type(var2) == str:
          print('your variable is a string')
      else:
          print('your variable IS NOT a string')
      

      希望这会有所帮助!

      【讨论】:

      • 最好使用 type(var) is int,因为 PEP8 不建议使用 == 来比较类型
      【解决方案6】:

      以下是我对支持 Python 2 和 Python 3 以及这些要求的回答:

      • 用 Py3 代码编写,使用最少的 Py2 兼容代码。
      • 稍后删除 Py2 兼容代码而不会中断。 IE。只针对删除,不修改 Py3 代码。
      • 避免使用six 或类似的兼容模块,因为它们往往会隐藏什么 正在努力实现。
      • 面向未来的潜在 Py4。

      import sys
      PY2 = sys.version_info.major == 2
      
      # Check if string (lenient for byte-strings on Py2):
      isinstance('abc', basestring if PY2 else str)
      
      # Check if strictly a string (unicode-string):
      isinstance('abc', unicode if PY2 else str)
      
      # Check if either string (unicode-string) or byte-string:
      isinstance('abc', basestring if PY2 else (str, bytes))
      
      # Check for byte-string (Py3 and Py2.7):
      isinstance('abc', bytes)
      

      【讨论】:

        【解决方案7】:

        我知道这是一个老话题,但作为第一个在 google 上显示的话题,鉴于我没有找到任何令人满意的答案,我将把它留在这里以供将来参考:

        six 是一个 Python 2 和 3 兼容库,已经涵盖了这个问题。然后你可以这样做:

        import six
        
        if isinstance(value, six.string_types):
            pass # It's a string !!
        

        检查代码,发现如下:

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

        【讨论】:

        • 例如对于单行:value_is_string = isinstance(value, str if sys.version_info[0] >= 3 else basestring),其中>= 假定任何最终的 Python 4+ 都保留 str 字符串的根类。
        • six 不是标准 Python 安装的一部分,因此几乎按照定义是不可移植的。我想编写一个简单的 Python 应用程序,让它对任何运行它的人都“正常工作”。如果我告诉他们“首先,您需要安装这个 other 库,只需使用我的应用程序即可”,这是一个大问题。
        • 这就是实现代码存在的原因。
        • six 库似乎仅适用于我 Mac 上的 Python2。如果它的可用性是特定于版本的,那么您不妨首先使用其中一个特定于版本的解决方案。
        • 代码扩展的内容写在那里。你可以用那个。关键是这里的其他答案是错误的,根据 Python 库认为的字符串类型。
        【解决方案8】:

        这里有很多其他人提供的好建议,但我没有看到一个好的跨平台总结。对于任何 Python 程序,以下内容应该是一个不错的选择:

        def isstring(s):
            # if we use Python 3
            if (sys.version_info[0] >= 3):
                return isinstance(s, str)
            # we use Python 2
            return isinstance(s, basestring)
        

        在这个函数中,我们使用 isinstance(object, classinfo) 来查看我们的输入是 Python 3 中的 str 还是 Python 2 中的 basestring

        【讨论】:

        • 这可能会在 Python 4 中中断,至少考虑 >=
        • 更干净地检查 Six.string_types 或 Six.text_type
        • @daonb 导入整个模块只是为了进行单行测试,这种想法会导致疯狂的依赖树和严重的膨胀破坏原本应该是短小而简单的东西。这当然是你的电话,但只是说'n ...
        • @duanev 如果您担心 Python 2/3 兼容性,那么在项目中使用 6 个是一个更好的主意。六也是一个单个文件,所以依赖树/膨胀在这里不是问题。
        • 另外,至少在我的 Mac 上,import six 在 Python3 中是一个错误
        【解决方案9】:

        Python 2 / 3 包括 unicode

        from __future__ import unicode_literals
        from builtins import str  #  pip install future
        isinstance('asdf', str)   #  True
        isinstance(u'asdf', str)  #  True
        

        http://python-future.org/overview.html

        【讨论】:

        • 非常感谢!互联网上有几十种不同的答案,但唯一好的就是这个。第一行使type('foo') 在python 2 中默认为unicode,第二行使str 成为unicode 的实例。这些使代码在 Python 2 和 3 中有效。再次感谢!
        【解决方案10】:
        a = '1000' # also tested for 'abc100', 'a100bc', '100abc'
        
        isinstance(a, str) or isinstance(a, unicode)
        

        返回真

        type(a) in [str, unicode]
        

        返回真

        【讨论】:

        • 对于 Python 2.7.12,我必须删除引号: type(a) in [str, unicode]
        • 不适用于 Python3
        【解决方案11】:

        所以,

        你有很多选项来检查你的变量是否是字符串:

        a = "my string"
        type(a) == str # first 
        a.__class__ == str # second
        isinstance(a, str) # third
        str(a) == a # forth
        type(a) == type('') # fifth
        

        此命令是有目的的。

        【讨论】:

        • 这是一个很好的类型测试方法纲要。但是在 Python2 中,如果你认为 unicode 是字符串类型,这将不起作用。
        【解决方案12】:
        s = '123'
        issubclass(s.__class__, str)
        

        【讨论】:

          【解决方案13】:

          您可以简单地使用 isinstance 函数来确保输入数据的格式为 stringunicode。以下示例将帮助您轻松理解。

          >>> isinstance('my string', str)
          True
          >>> isinstance(12, str)
          False
          >>> isinstance('my string', unicode)
          False
          >>> isinstance(u'my string',  unicode)
          True
          

          【讨论】:

            【解决方案14】:

            由于basestring 没有在 Python3 中定义,这个小技巧可能有助于使代码兼容:

            try: # check whether python knows about 'basestring'
               basestring
            except NameError: # no, it doesn't (it's Python3); use 'str' instead
               basestring=str
            

            之后,您可以在 Python2 和 Python3 上运行以下测试

            isinstance(myvar, basestring)
            

            【讨论】:

            • 或者如果你也想捕获字节串:basestring = (str, bytes)
            【解决方案15】:

            在 Python 3.x 或 Python 2.7.6 中

            if type(x) == str:
            

            【讨论】:

            • 我喜欢“if type(x) in (str, unicode):”的优雅,但我看到 PyLint 将其标记为“unidiomatic”。
            • PEP8 明确不鼓励将类型与== 进行比较,并且除了被认为是“单一的”之外还有几个缺点,例如它不检测str 的子类实例,这些实例也应被视为字符串。如果您真的想准确检查 str 类型并明确排除子类,请使用 type(x) is str
            • @SvenMarnach 那么应该使用 isinstance 来包含子类吗?
            • @sinekonata 是的,检查字符串的最常见和推荐的方法是 Python 3.x 中的isinstance(s, str) - 请参阅上面的答案。仅当您有特定原因排除子类时(应该很少见),您应该使用type(s) is str
            • type(x) == str 不适用于 Python2 中的 unicode 字符串。 type(x) in (str, unicode) 是 Python3 中的错误。
            【解决方案16】:

            根据以下更好的答案进行编辑。下来大概3个答案,了解一下basestring的酷炫吧。

            旧答案: 注意 unicode 字符串,您可以从多个位置获取这些字符串,包括 Windows 中的所有 COM 调用。

            if isinstance(target, str) or isinstance(target, unicode):
            

            【讨论】:

            • 好收获。我不知道basestring。提到了大约 3 个帖子,似乎是一个更好的答案。
            • isinstance() 也将 tuple 作为第二个参数。所以即使basestring不存在,你也可以使用isinstance(target, (str, unicode))
            • 在 python 3.5.1 中,unicode 似乎没有被定义:NameError: name 'unicode' is not defined
            【解决方案17】:

            我见过:

            hasattr(s, 'endswith') 
            

            【讨论】:

              【解决方案18】:

              这就是我的做法:

              if type(x) == type(str()):
              

              【讨论】:

              • type(str()) 是一种非常迂回的说法str。类型是单例,所以type(x) is str 更有效。应该改用isinstance(),除非您有充分的理由忽略str 的子类。
              • 如果 type(x) 是 str:
              【解决方案19】:

              如果您不想依赖外部库,这适用于 Python 2.7+ 和 Python 3 (http://ideone.com/uB4Kdc):

              # your code goes here
              s = ["test"];
              #s = "test";
              isString = False;
              
              if(isinstance(s, str)):
                  isString = True;
              try:
                  if(isinstance(s, basestring)):
                      isString = True;
              except NameError:
                  pass;
              
              if(isString):
                  print("String");
              else:
                  print("Not String");
              

              【讨论】:

                【解决方案20】:

                另外我要注意,如果要检查变量的类型是否为特定类型,可以将变量的类型与已知对象的类型进行比较。

                对于字符串,你可以使用这个

                type(s) == type('')
                

                【讨论】:

                • 这是在 python 中输入检查的一种糟糕的、糟糕的方式。如果另一个类继承自str 怎么办? unicode 字符串呢,它甚至不继承自 2.x 中的str?在 2.x 中使用 isinstance(s, basestring),在 3.x 中使用 isinstance(s, str)
                • @Jack,请阅读问题,并注意我没有写这是最好的方式,只是另一种方式。
                • 这是一个坏主意,有 3 个原因:isinstance() 允许子类(它们也是字符串,只是专门化的),额外的 type('') 调用是多余的,当你可以使用 str 和类型是单例,所以type(s) is str 将是一个更有效的测试。
                【解决方案21】:

                Python 2 的替代方法,不使用基本字符串:

                isinstance(s, (str, unicode))
                

                但在 Python 3 中仍然无法使用,因为 unicode 未定义(在 Python 3 中)。

                【讨论】:

                  【解决方案22】:

                  如果您检查的不仅仅是整数和字符串,类型模块也存在。 http://docs.python.org/library/types.html

                  【讨论】:

                  • 更具体地说,types.StringTypes
                  • types.StringTypes 在 Python 3 中似乎不再存在 :(
                  • types.StringTypes 没有为 Python3 定义
                  猜你喜欢
                  • 2013-12-15
                  • 2020-04-25
                  • 2013-09-04
                  • 2020-05-28
                  • 2012-04-13
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-01-25
                  • 2015-11-03
                  相关资源
                  最近更新 更多