471

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

4

15 回答 15

314

蟒蛇2

用于isinstance(obj, basestring)测试对象obj

文档

于 2009-08-19T23:53:12.203 回答
258

蟒蛇 3

在 Python 3.xbasestring中不再可用,str唯一的字符串类型也是如此(具有 Python 2.x 的语义unicode)。

所以 Python 3.x 中的检查只是:

isinstance(obj_to_test, str)

这遵循官方转换工具的修复:转换为.2to3basestringstr

于 2014-10-23T19:19:58.297 回答
193

蟒蛇2

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

isinstance(o, basestring)

因为strunicode都是 的子类basestring

检查类型o是否准确str

type(o) is str

检查是否o是 的实例str或任何子类str

isinstance(o, str)

如果您替换为 . 以上也适用于 Unicodestr字符串unicode

但是,您可能根本不需要进行显式类型检查。“鸭子打字”可能适合您的需求。请参阅http://docs.python.org/glossary.html#term-duck-typing

另请参阅在 python 中检查类型的规范方法是什么?

于 2009-08-19T23:58:15.033 回答
97

Python 2 和 3

(交叉兼容)

如果您想检查而不考虑 Python 版本(2.x 与 3.x),请使用sixPyPI)及其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
于 2014-05-16T03:57:49.477 回答
23

我发现了更多pythonic

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

由于类型对象是单例的,因此可用于将对象与 str 类型进行比较

于 2016-06-14T09:53:58.407 回答
16

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

str(maybe_string) == maybe_string

它不会遍历可迭代对象或迭代器,不会将字符串列表称为字符串,并且会正确地将类似字符串的字符串检测为字符串

当然也有缺点。例如,str(maybe_string)可能是一个繁重的计算。通常,答案是视情况而定。

编辑:正如@Tcll在评论中 指出的那样,这个问题实际上要求一种检测 unicode 字符串和字节串的方法。在 Python 2 上,此答案将失败,但包含非 ASCII 字符的 unicode 字符串会出现异常,而在 Python 3 上,它将返回False所有字节串。

于 2016-07-28T12:44:46.970 回答
13

为了检查你的变量是否是你可以这样的东西:

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

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

于 2016-06-30T13:26:15.967 回答
6

它很简单,使用以下代码(我们假设提到的对象是 obj) -

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')
于 2020-03-31T07:03:49.867 回答
5

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

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

如果 arg 已经是字符串或 unicode 类型,real_word 将保持其值不变。如果传递的对象实现了一个__unicode__方法,则该方法用于获取其 unicode 表示。如果传递的对象不能用作字符串,则unicode内置函数会引发异常。

于 2009-08-21T17:50:16.583 回答
3
isinstance(your_object, basestring)

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

抱歉,正确的答案是使用“basestring”而不是“str”,以便它也包含 unicode 字符串——正如上面其他响应者之一所指出的那样。

于 2014-03-19T09:35:26.223 回答
1

今天晚上我遇到了一种情况,我以为我必须检查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
于 2017-07-21T04:00:39.323 回答
0

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

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

编辑

在评论指出列表失败后更正我的答案

def is_string(s):
  return isinstance(s, basestring)
于 2013-01-24T14:48:52.797 回答
0

我认为可以安全地假设,如果输出的最后一个字符repr()是 a 'or ",那么无论它是什么,它都应该被认为是某种字符串。

def isStr(o):
    return repr(o)[-1] in '\'"'

我假设它repr不会做任何太重的事情,并且它会返回一个至少包含一个字符的字符串。您可以使用类似的东西来支持空字符串

repr(o)[-1:].replace('"', "'") == "'"

但这仍然假设repr返回一个字符串。

于 2021-10-08T01:39:27.700 回答
-4
if type(varA) == str or type(varB) == str:
    print 'string involved'

来自 EDX - 在线课程 MITx: 6.00.1x Introduction to Computer Science and Programming Using Python

于 2014-09-11T23:38:26.480 回答
-4

对于类似字符串的一种很好的鸭子类型方法,它具有同时使用 Python 2.x 和 3.x 的好处:

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

wisefish在改用这种方法之前与鸭式打字很接近,但isinstance它对+=列表的含义与实际不同+

于 2014-11-16T22:51:39.147 回答