ChatGPT解决这个技术问题 Extra ChatGPT

如何检查变量的类型是否为字符串?

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

isinstance(x,int);

对于整数值?

如果您正在学习 python canonical.org/~kragen/isinstance,则需要阅读 isinstance。
isinstance(True, int) is True 开始注意整数。
isinstance(x,str) 在 Python 3 中是正确的(str 是基本类型)。
简单地说:type(my_variable) is str怎么样? I made this an answer

S
Sven Marnach

在 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 个对象,这些对象也应该被视为字符串。类型 str 和类型 unicode 都具有公共基类 basestring,这就是您要检查的内容。
@Yarin 如果您要将某些内容从 2.x 移植到 3.x,则始终可以分配 basestring = str
@AdamErickson 到底兼容什么?它对与 Python 3 的兼容性没有帮助,因为 Python 3 中没有 unicode。我对 Python 2 和 3 之间的兼容性的建议是使用“six”库。 (在这种情况下特别是 isintance(s, six.string_types)
A
André Fratelli

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

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 根类。
不是标准 Python 安装的一部分,因此几乎按照定义是不可移植的。我想编写一个简单的 Python 应用程序,让它对任何运行它的人都“正常工作”。如果我告诉他们“首先,您需要安装这个其他库,只需使用我的应用程序”,这是一个大问题。
这就是实现代码存在的原因。
six 库似乎仅适用于我 Mac 上的 Python2。如果它的可用性是特定于版本的,那么您不妨首先使用一个特定于版本的解决方案。
代码扩展成的内容写在那里。你可以用那个。关键是这里的其他答案是错误的,根据 Python 库认为的字符串类型。
T
Texom512

在 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 中的错误。
i
ivanleoncz

你可以做:

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 不建议使用 == 来比较类型
G
Gabriel Staples

使用 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))

输出:

真假真假


d
dicato

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


更具体地说,types.StringTypes
types.StringTypes 在 Python 3 中似乎不再存在 :(
types.StringTypes 未为 Python3 定义
W
Wade Hatler

根据以下更好的答案进行编辑。下去大约 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
u
umläute

由于 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)
c
crizCraig

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 中有效。再次感谢!
P
PatNowak

所以,

您有很多选项可以检查您的变量是否为字符串:

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 是字符串类型,这将不起作用。
d
duanev

其他人在这里提供了很多好的建议,但我没有看到一个好的跨平台总结。对于任何 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 中的错误
D
Daniil Grankin

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

对于字符串,您可以使用它

type(s) == type('')

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

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

isinstance(s, (str, unicode))

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


C
Cas

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

用最少的 Py2 兼容代码用 Py3 代码编写。

稍后删除 Py2 兼容代码而不会中断。即只针对删除,不修改 Py3 代码。

避免使用六个或类似的兼容模块,因为它们往往会隐藏试图实现的目标。

面向未来的潜在 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)

b
be_good_do_good
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
m
mPrinC

如果您不想依赖外部库,这适用于 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");

H
Hassan Mehmood

您可以简单地使用 isinstance 函数来确保输入数据是格式字符串或 unicode。以下示例将帮助您轻松理解。

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

E
Edward Falk

总结:

如果您同时需要 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 感到有些震惊。我认为没有理由放弃它们,保留它们中的任何一个都可以解决这个问题。


v
vadim vaduxa
s = '123'
issubclass(s.__class__, str)

U
User

我就是这样做的:

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

type(str())str 的一种非常迂回的说法。类型是单例的,所以 type(x) is str 更有效。应改为使用 isinstance(),除非您有充分的理由忽略 str 的子类。
如果 type(x) 是 str:
f
fast tooth

我见过:

hasattr(s, 'endswith') 

R
Richard Urban
>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True

在哪种情况下,您更喜欢 type(thing).__name__ == 'str' 而不是 type(thing) == strisinstance(thing, str)?此外,现代版本的 Python 中也不存在 unicode