# 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
281
为了检查你的变量是否适合你:
s='Hello World'
if isinstance(s,str):
#do something here,
13 回答
Python 3
在Python 3.x中,
basestring
不再可用,因为str
是唯一的字符串类型(具有Python 2.x的unicode
的语义) .因此,Python 3.x中的检查只是:
这是在官方
2to3
转换工具的the fix之后:将basestring
转换为str
.如果想要远离显式类型检查(并且有充分的理由远离它),可能要检查的字符串协议中最安全的部分是:
它赢得了't iterate through an iterable or iterator, it won' t调用字符串列表字符串并且它正确地将stringlike检测为字符串 .
当然有缺点 . 例如,
str(maybe_string)
可能是一个繁重的计算 . 通常,答案取决于它 .要检查对象
o
是否是字符串类型的子类的字符串类型:因为
str
和unicode
都是basestring
的子类 .要检查
o
的类型是否完全是str
:要检查
o
是str
的实例还是str
的任何子类:如果将
str
替换为unicode
,则上述内容也适用于Unicode字符串 .但是,您可能根本不需要进行显式类型检查 . "Duck typing"可能符合您的需求 . 见http://docs.python.org/glossary.html#term-duck-typing .
另见What’s the canonical way to check for type in python?
您可以通过连接空字符串来测试它:
Edit :
在评论指出这与列表失败后纠正我的答案
如果您的对象确实是字符串类型,则为True . 'str'是保留字 .
我的道歉,正确的答案是使用'basestring'而不是'str',以便它包括unicode字符串 - 正如上面其他响应者之一所述 .
Python 2和3
(交叉兼容)
如果你想检查不考虑Python版本(2.x vs 3.x),请使用six(PyPI)及其
string_types
属性:在
six
(一个非常轻量级的单文件模块)中,它只是做this:Python 2
使用
isinstance(obj, basestring)
进行对象测试obj
.Docs .
今天晚上我遇到了一个情况,我不得不检查
str
类型,但事实证明我没有 .我解决问题的方法可能适用于很多情况,所以我在下面提供它以防其他人阅读这个问题感兴趣(仅限Python 3) .
一些测试:
为了检查你的变量是否适合你:
isistance的输出将为您提供布尔值True或False值,以便您可以相应地进行调整 . 您可以通过最初使用来检查值的预期首字母缩写:type(s)这将返回键入'str',以便您可以在isistance函数中使用它 .
对于一个很好的鸭子类型的方法,可以使用Python 2.x和3.x:
wisefish在切换到
isinstance
方法之前与鸭子打字很接近,除了+=
对列表的含义不同于+
.我发现这个更加pythonic:
由于类型对象是单例,因此可以使用 is 进行比较
我可能会像其他人提到的那样以鸭子打字的方式处理这个问题 . 我怎么知道字符串真的是一个字符串?好吧,显然通过将其转换为字符串!
如果arg已经是字符串或unicode类型,则real_word将保持其值不被修改 . 如果传递的对象实现
__unicode__
方法,则用于获取其unicode表示 . 如果传递的对象不能用作字符串,则unicode
builtin会引发异常 .来自EDX - 在线课程MITx:6.00.1x计算机科学和使用Python编程简介