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

有没有一种方法可以检查python中变量的类型是否为string,例如:

isinstance(x,int);

对于整数值?

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

isinstance(x,int);

for integer values?


回答 0

在Python 2.x中,您可以

isinstance(s, basestring)

basestring抽象的超类strunicode。它可用于测试对象是否是str或的实例unicode


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

isinstance(s, str)

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

In Python 2.x, you would do

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.


In Python 3.x, the correct test is

isinstance(s, str)

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


回答 1

我知道这是一个古老的话题,但是作为第一个显示在google上的话题,鉴于我没有找到满意的答案,因此我将其留在此处以供将来参考:

第六个是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,

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:

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,

回答 2

在Python 3.x或Python 2.7.6中

if type(x) == str:

In Python 3.x or Python 2.7.6

if type(x) == str:

回答 3

你可以做:

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')

希望这可以帮助!

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!


回答 4

如果要检查的内容多于整数和字符串,则类型模块也存在。 http://docs.python.org/library/types.html

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


回答 5

根据以下更好的答案进行编辑。记下3个答案,找出基弦的凉爽。

旧答案:当心unicode字符串,您可以从多个地方获得unicode字符串,包括Windows中的所有COM调用。

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

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

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

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

回答 6

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

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

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

isinstance(myvar, basestring)

回答 7

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

Python 2 / 3 including 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


回答 8

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

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

type(s) == type('')

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

其他人在这里提供了很多好的建议,但是我看不到一个很好的跨平台摘要。对于任何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)查看输入是str在Python 3中还是basestring在Python 2中。

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:

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.


回答 10

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

isinstance(s, (str, unicode))

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

Alternative way for Python 2, without using basestring:

isinstance(s, (str, unicode))

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


回答 11

所以,

您可以使用很多选项来检查变量是否为字符串:

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

此命令是有目的的。

So,

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

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.


回答 12

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

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

返回True

type(a) in [str, unicode]

返回True

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

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

returns True

type(a) in [str, unicode]

returns True


回答 13

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

  • 用最少的Py2兼容代码以Py3代码编写。
  • 稍后删除Py2兼容代码而不会受到干扰。即仅旨在删除,不修改Py3代码。
  • 避免使用 six或类似的compat模块,因为它们倾向于隐藏试图实现的目标。
  • 面向未来的潜在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)

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

  • Written in Py3 code with minimal Py2 compat code.
  • Remove Py2 compat code later without disruption. I.e. aim for deletion only, no modification to Py3 code.
  • Avoid using six or similar compat module as they tend to hide away what is trying to be achieved.
  • Future-proof for a potential 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)

回答 14

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

If you do not want to depend on external libs, this works both for Python 2.7+ and 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");

回答 15

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

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

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('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string',  unicode)
True

回答 16

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

回答 17

这是我的方法:

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

This is how I do it:

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

回答 18

我见过:

hasattr(s, 'endswith') 

I’ve seen:

hasattr(s, 'endswith') 

回答 19

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。