如何检查Python对象是否为字符串(常规或Unicode)?
当前回答
为了检查你的变量是不是你可以这样做:
s='Hello World'
if isinstance(s,str):
#do something here,
阻力的输出会给你一个布尔值True或False,这样你就可以相应地调整。 你可以通过以下方法检查你的值的首字母缩写: 类型(年代) 这将返回您键入'str',以便您可以在isistance函数中使用它。
其他回答
对于类似字符串的良好鸭子类型方法,它具有与Python 2同时使用的好处。X和3.x:
def is_string(obj):
try:
obj + ''
return True
except TypeError:
return False
Wisefish在切换到isinstance方法之前与duck-typing很接近,只是+=对于列表的含义与+不同。
我可能会像其他人提到的那样,用鸭子类型来处理这个问题。我怎么知道一个字符串真的是一个字符串?显然是通过将其转换为字符串!
def myfunc(word):
word = unicode(word)
...
如果arg已经是一个字符串或unicode类型,real_word将保持其值不变。如果传递的对象实现了__unicode__方法,则该方法用于获取其unicode表示。如果传递的对象不能作为字符串使用,unicode内置将引发异常。
我发现这句话更夸张:
if type(aObject) is str:
#do your stuff here
pass
由于类型对象是单例的,is可以用来比较对象和STR类型
今天晚上,我遇到了一种情况,我认为我必须检查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
对于测试对象obj,使用isinstance(obj, basestring)。
文档。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- 将整数转换为字符串,以逗号表示千
- Python日志记录不输出任何东西
- 将JavaScript字符串中的多个空格替换为单个空格
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?