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

时间:2020-12-14 16:27:09

Is there a way to check if the type of a variable in python is string.. like

是否有办法检查python中变量的类型是否是字符串。就像

isinstance(x,int);

for integer values?

整数值吗?

23 个解决方案

#1


705  

In Python 2.x, you would do

在Python中2。x,你会做

isinstance(s, basestring)

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.

basestring是str和unicode的抽象超类。它可以用来测试对象是str实例还是unicode实例。


In Python 3.x, the correct test is

Python 3。x,正确的测试是

isinstance(s, str)

The bytes class isn't considered a string type in Python 3.

在python3中,字节类不被认为是字符串类型。

#2


186  

I know this is an old topic, but being the first one shown on google and given that I don't find any of the answers satisfactory, I'll leave this here for future reference:

我知道这是一个老话题,但作为谷歌上的第一个,我没有找到任何满意的答案,我把这个留给以后参考:

six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:

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

import six

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

Inspecting the code, this is what you find:

检查代码,你会发现:

import sys

PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str,
else:
    string_types = basestring,

#3


35  

In Python 3.x or Python 2.7.6

Python 3。x或Python 2.7.6

if type(x) == str:

#4


14  

The type module also exists if you are checking more than ints and strings. http://docs.python.org/library/types.html

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

#5


10  

Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.

根据下面更好的答案进行编辑。找出大约3个答案,找出关于棒球的酷感。

Old answer: Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.

老办法:注意unicode字符串,你可以从几个地方获得,包括Windows中的所有COM调用。

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

#6


9  

since basestring isn't defined in Python3, this little trick might help to make the code compatible:

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

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

after that you can run the following test on both Python2 and Python3

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

isinstance(myvar, basestring)

#7


8  

Lots of good suggestions provided by others here, but I don't see a good cross-platform summary. The following should be a good drop in for any Python program:

这里有很多好的建议,但是我没有看到一个好的跨平台的总结。对于任何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)

In this function, we use isinstance(object, classinfo) to see if our input is a str in Python 3 or a basestring in Python 2.

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

#8


7  

Also I want notice that if you want to check whether the type of a variable is a specific kind, you can compare the type of the variable to the type of a known object.

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

For string you can use this

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

type(s) == type('')

#9


6  

Python 2 / 3 including unicode

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

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

#10


6  

you can do:

你能做什么:

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

or:

或者:

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

hope this helps!

希望这可以帮助!

#11


4  

Alternative way for Python 2, without using basestring:

Python 2的替代方法,不使用basestring:

isinstance(s, (str, unicode))

But still won't work in Python 3 since unicode isn't defined (in Python 3).

但是在Python 3中仍然不能工作,因为unicode没有定义(在Python 3中)。

#12


4  

a = '1000' # also tested for 'abc100', 'a100bc', '100abc'

isinstance(a, str) or isinstance(a, unicode)

returns True

返回True

type(a) in [str, unicode]

returns True

返回True

#13


3  

So,

所以,

You have plenty of options to check whether your variable is string or not:

您有很多选项可以检查变量是否为string:

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

This order is for purpose.

这个订单是有目的的。

#14


3  

Here is my answer to support both Python 2 and Python 3 along with these requirements:

下面是我支持Python 2和Python 3以及以下要求的答案:

  • Written in Py3 code with minimal Py2 compat code.
  • 用最小的Py2编译代码编写的Py3代码。
  • Remove Py2 compat code later without disruption. I.e. aim for deletion only, no modification to Py3 code.
  • 稍后在不中断的情况下删除Py2编译代码。即只针对删除,不修改Py3代码。
  • Avoid using six or similar compat module as they tend to hide away what is trying to be achieved.
  • 避免使用6个或类似的compat模块,因为它们倾向于隐藏要实现的内容。
  • Future-proof for a potential Py4.
  • 对一个可能的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)

#15


2  

To test whether myvar is a string, can also use this:

为了测试myvar是否是一个字符串,还可以使用以下方法:

if type(myvar) == str

#16


1  

If you do not want to depend on external libs, this works both for Python 2.7+ and Python 3 (http://ideone.com/uB4Kdc):

如果您不想依赖外部libs,那么这对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");

#17


0  

You can simply use the isinstance function to make sure that the input data is of format string or unicode. Below examples will help you to understand easily.

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

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

#18


-1  

s = '123'
issubclass(s.__class__, str)

#19


-3  

This is how I do it:

我是这样做的:

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

#20


-3  

varA = "hey"
if type(varA) == str:
   print "it is a string"

#21


-4  

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

#22


-5  

I've seen:

我看过:

hasattr(s, 'endswith') 

#23


-5  

To test whether myvar is a string, use this:

要测试myvar是否是字符串,请使用以下命令:

if type(myvar) == type('abc')

#1


705  

In Python 2.x, you would do

在Python中2。x,你会做

isinstance(s, basestring)

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.

basestring是str和unicode的抽象超类。它可以用来测试对象是str实例还是unicode实例。


In Python 3.x, the correct test is

Python 3。x,正确的测试是

isinstance(s, str)

The bytes class isn't considered a string type in Python 3.

在python3中,字节类不被认为是字符串类型。

#2


186  

I know this is an old topic, but being the first one shown on google and given that I don't find any of the answers satisfactory, I'll leave this here for future reference:

我知道这是一个老话题,但作为谷歌上的第一个,我没有找到任何满意的答案,我把这个留给以后参考:

six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:

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

import six

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

Inspecting the code, this is what you find:

检查代码,你会发现:

import sys

PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str,
else:
    string_types = basestring,

#3


35  

In Python 3.x or Python 2.7.6

Python 3。x或Python 2.7.6

if type(x) == str:

#4


14  

The type module also exists if you are checking more than ints and strings. http://docs.python.org/library/types.html

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

#5


10  

Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.

根据下面更好的答案进行编辑。找出大约3个答案,找出关于棒球的酷感。

Old answer: Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.

老办法:注意unicode字符串,你可以从几个地方获得,包括Windows中的所有COM调用。

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

#6


9  

since basestring isn't defined in Python3, this little trick might help to make the code compatible:

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

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

after that you can run the following test on both Python2 and Python3

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

isinstance(myvar, basestring)

#7


8  

Lots of good suggestions provided by others here, but I don't see a good cross-platform summary. The following should be a good drop in for any Python program:

这里有很多好的建议,但是我没有看到一个好的跨平台的总结。对于任何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)

In this function, we use isinstance(object, classinfo) to see if our input is a str in Python 3 or a basestring in Python 2.

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

#8


7  

Also I want notice that if you want to check whether the type of a variable is a specific kind, you can compare the type of the variable to the type of a known object.

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

For string you can use this

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

type(s) == type('')

#9


6  

Python 2 / 3 including unicode

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

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

#10


6  

you can do:

你能做什么:

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

or:

或者:

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

hope this helps!

希望这可以帮助!

#11


4  

Alternative way for Python 2, without using basestring:

Python 2的替代方法,不使用basestring:

isinstance(s, (str, unicode))

But still won't work in Python 3 since unicode isn't defined (in Python 3).

但是在Python 3中仍然不能工作,因为unicode没有定义(在Python 3中)。

#12


4  

a = '1000' # also tested for 'abc100', 'a100bc', '100abc'

isinstance(a, str) or isinstance(a, unicode)

returns True

返回True

type(a) in [str, unicode]

returns True

返回True

#13


3  

So,

所以,

You have plenty of options to check whether your variable is string or not:

您有很多选项可以检查变量是否为string:

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

This order is for purpose.

这个订单是有目的的。

#14


3  

Here is my answer to support both Python 2 and Python 3 along with these requirements:

下面是我支持Python 2和Python 3以及以下要求的答案:

  • Written in Py3 code with minimal Py2 compat code.
  • 用最小的Py2编译代码编写的Py3代码。
  • Remove Py2 compat code later without disruption. I.e. aim for deletion only, no modification to Py3 code.
  • 稍后在不中断的情况下删除Py2编译代码。即只针对删除,不修改Py3代码。
  • Avoid using six or similar compat module as they tend to hide away what is trying to be achieved.
  • 避免使用6个或类似的compat模块,因为它们倾向于隐藏要实现的内容。
  • Future-proof for a potential Py4.
  • 对一个可能的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)

#15


2  

To test whether myvar is a string, can also use this:

为了测试myvar是否是一个字符串,还可以使用以下方法:

if type(myvar) == str

#16


1  

If you do not want to depend on external libs, this works both for Python 2.7+ and Python 3 (http://ideone.com/uB4Kdc):

如果您不想依赖外部libs,那么这对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");

#17


0  

You can simply use the isinstance function to make sure that the input data is of format string or unicode. Below examples will help you to understand easily.

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

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

#18


-1  

s = '123'
issubclass(s.__class__, str)

#19


-3  

This is how I do it:

我是这样做的:

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

#20


-3  

varA = "hey"
if type(varA) == str:
   print "it is a string"

#21


-4  

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

#22


-5  

I've seen:

我看过:

hasattr(s, 'endswith') 

#23


-5  

To test whether myvar is a string, use this:

要测试myvar是否是字符串,请使用以下命令:

if type(myvar) == type('abc')