如何检查Python对象是否为字符串(常规或Unicode)?
当前回答
isinstance(your_object, basestring)
如果对象确实是字符串类型,则为True。'str'是保留字。
我的道歉, 正确的答案是使用'basestring'而不是'str',以便它也包括unicode字符串-正如上面其他响应者之一所指出的那样。
其他回答
它很简单,使用以下代码(我们假设提到的对象是obj)-
if type(obj) == str:
print('It is a string')
else:
print('It is not a string.')
今天晚上,我遇到了一种情况,我认为我必须检查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
Python 2
检查对象o是否是字符串类型的子类的字符串类型:
isinstance(o, basestring)
因为STR和unicode都是basestring的子类。
要检查o的类型是否恰好是str:
type(o) is str
检查o是否是str的实例或str的任何子类:
isinstance(o, str)
如果将str替换为Unicode,上述方法也适用于Unicode字符串。
但是,您可能根本不需要进行显式类型检查。“鸭子打字”可能适合你的需要。见http://docs.python.org/glossary.html # term-duck-typing。
参见python中检查类型的规范方法是什么?
Python 2和3
(cross-compatible)
如果你想检查不考虑Python版本(2。x vs . 3.x),使用six (PyPI)及其string_types属性:
import six
if isinstance(obj, six.string_types):
print('obj is a string!')
在六个(一个非常轻量级的单文件模块)中,它只是这样做的:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str
else:
string_types = basestring
if type(varA) == str or type(varB) == str:
print 'string involved'
从 EDX -在线课程 MITx: 6.00.1x使用Python的计算机科学和编程介绍
推荐文章
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- indexOf()和search()的区别是什么?
- 存在类型是什么?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 我如何在Swift连接字符串?
- 要列出Pandas DataFrame列
- 如何连接列在Postgres选择?
- 在Django模型中存储电话号码的最佳方法是什么?