问题:如何找出Python对象是否是字符串?
如何检查Python对象是字符串(常规还是Unicode)?
How can I check if a Python object is a string (either regular or Unicode)?
回答 0
Python 2
使用isinstance(obj, basestring)
一个对象来测试obj
。
文件。
Python 2
Use isinstance(obj, basestring)
for an object-to-test obj
.
Docs.
回答 1
Python 2
To check if an object o
is a string type of a subclass of a string type:
isinstance(o, basestring)
because both str
and unicode
are subclasses of basestring
.
To check if the type of o
is exactly str
:
type(o) is str
To check if o
is an instance of str
or any subclass of str
:
isinstance(o, str)
The above also work for Unicode strings if you replace str
with unicode
.
However, you may not need to do explicit type checking at all. “Duck typing” may fit your needs. See http://docs.python.org/glossary.html#term-duck-typing.
See also What’s the canonical way to check for type in python?
回答 2
Python 3
在Python 3.x basestring
中,str
唯一的字符串类型(具有Python 2.x的语义unicode
)不再可用。
因此,Python 3.x中的检查只是:
isinstance(obj_to_test, str)
这是对官方转换工具的修复2to3
:转换basestring
为str
。
Python 3
In Python 3.x basestring
is not available anymore, as str
is the sole string type (with the semantics of Python 2.x’s unicode
).
So the check in Python 3.x is just:
isinstance(obj_to_test, str)
This follows the fix of the official 2to3
conversion tool: converting basestring
to str
.
回答 3
Python 2和3
(兼容)
如果您不想检查Python版本(2.x与3.x),请使用six
(PyPI)及其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
Python 2 and 3
(cross-compatible)
If you want to check with no regard for Python version (2.x vs 3.x), use six
(PyPI) and its string_types
attribute:
import six
if isinstance(obj, six.string_types):
print('obj is a string!')
Within six
(a very light-weight single-file module), it’s simply doing this:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str
else:
string_types = basestring
回答 4
我发现了这个更多pythonic
:
if type(aObject) is str:
#do your stuff here
pass
由于类型对象是单例,因此可以用于将对象与str类型进行比较
I found this ans more pythonic
:
if type(aObject) is str:
#do your stuff here
pass
since type objects are singleton, is can be used to do the compare the object to the str type
回答 5
如果一个人想从明确的类型检查(也有说走就走是很好的理由远离它),可能是最安全的弦协议的一部分,以检查:
str(maybe_string) == maybe_string
它不会通过迭代的迭代或迭代器,它不会调用列表的串一个字符串,它正确地检测弦乐器的弦。
当然有缺点。例如,str(maybe_string)
可能是繁重的计算。通常,答案取决于它。
编辑:作为@Tcll 指出的意见,问题实际上询问的方式同时检测unicode字符串和字节串。在Python 2上,此答案将失败,但包含非ASCII字符的unicode字符串将exceptions,在Python 3上,它将False
为所有字节串返回。
If one wants to stay away from explicit type-checking (and there are good reasons to stay away from it), probably the safest part of the string protocol to check is:
str(maybe_string) == maybe_string
It won’t iterate through an iterable or iterator, it won’t call a list-of-strings a string and it correctly detects a stringlike as a string.
Of course there are drawbacks. For example, str(maybe_string)
may be a heavy calculation. As so often, the answer is it depends.
EDIT: As @Tcll points out in the comments, the question actually asks for a way to detect both unicode strings and bytestrings. On Python 2 this answer will fail with an exception for unicode strings that contain non-ASCII characters, and on Python 3 it will return False
for all bytestrings.
回答 6
为了检查您的变量是否是某些东西,您可以像这样:
s='Hello World'
if isinstance(s,str):
#do something here,
isistance的输出将为您提供布尔值True或False,以便您可以进行相应的调整。您可以通过最初使用以下命令检查您的值的期望首字母缩写:type(s)这将返回您键入“ str”,以便您可以在isistance函数中使用它。
In order to check if your variable is something you could go like:
s='Hello World'
if isinstance(s,str):
#do something here,
The output of isistance will give you a boolean True or False value so you can adjust accordingly.
You can check the expected acronym of your value by initially using:
type(s)
This will return you type ‘str’ so you can use it in the isistance function.
回答 7
我可能会像其他人提到的那样以鸭子打字的方式处理这个问题。我怎么知道一个字符串真的是一个字符串?好吧,显然是通过将其转换为字符串!
def myfunc(word):
word = unicode(word)
...
如果arg已经是字符串或unicode类型,则real_word将保持其值不变。如果传递的对象实现一个__unicode__
方法,则该方法用于获取其unicode表示形式。如果传递的对象不能用作字符串,则unicode
内建函数引发异常。
I might deal with this in the duck-typing style, like others mention. How do I know a string is really a string? well, obviously by converting it to a string!
def myfunc(word):
word = unicode(word)
...
If the arg is already a string or unicode type, real_word will hold its value unmodified. If the object passed implements a __unicode__
method, that is used to get its unicode representation. If the object passed cannot be used as a string, the unicode
builtin raises an exception.
回答 8
isinstance(your_object, basestring)
如果您的对象确实是字符串类型,则将为True。’str’是保留字。
抱歉,正确的答案是使用’basestring’而不是’str’,以便它也包括unicode字符串-如上文其他响应者所述。
isinstance(your_object, basestring)
will be True if your object is indeed a string-type. ‘str’ is reserved word.
my apologies,
the correct answer is using ‘basestring’ instead of ‘str’ in order of it to include unicode strings as well – as been noted above by one of the other responders.
回答 9
今天晚上,我遇到了一种情况,我以为我必须检查一下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
This evening I ran into a situation in which I thought I was going to have to check against the str
type, but it turned out I did not.
My approach to solving the problem will probably work in many situations, so I offer it below in case others reading this question are interested (Python 3 only).
# 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
Some tests:
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
回答 10
它很简单,请使用以下代码(我们假设提到的对象为obj)-
if type(obj) == str:
print('It is a string')
else:
print('It is not a string.')
Its simple, use the following code (we assume the object mentioned to be obj)-
if type(obj) == str:
print('It is a string')
else:
print('It is not a string.')
回答 11
您可以通过连接一个空字符串来测试它:
def is_string(s):
try:
s += ''
except:
return False
return True
编辑:
在指出指出列表失败的评论后纠正我的答案
def is_string(s):
return isinstance(s, basestring)
You can test it by concatenating with an empty string:
def is_string(s):
try:
s += ''
except:
return False
return True
Edit:
Correcting my answer after comments pointing out that this fails with lists
def is_string(s):
return isinstance(s, basestring)
回答 12
对于类似字符串的鸭式打字方法,它具有同时使用Python 2.x和3.x的优点:
def is_string(obj):
try:
obj + ''
return True
except TypeError:
return False
明智的鱼在转而使用鸭式输入法之前就与鸭式输入isinstance
方式很接近,只是+=
对列表的含义与以前不同+
。
For a nice duck-typing approach for string-likes that has the bonus of working with both Python 2.x and 3.x:
def is_string(obj):
try:
obj + ''
return True
except TypeError:
return False
wisefish was close with the duck-typing before he switched to the isinstance
approach, except that +=
has a different meaning for lists than +
does.
回答 13
if type(varA) == str or type(varB) == str:
print 'string involved'
来自EDX-在线类MITx:6.00.1x使用Python进行计算机科学和编程简介
if type(varA) == str or type(varB) == str:
print 'string involved'
from
EDX – online course
MITx: 6.00.1x Introduction to Computer Science and Programming Using Python