Mat*_* S. 172
要检查对象o是否是字符串类型的子类的字符串类型:
isinstance(o, basestring)
Run Code Online (Sandbox Code Playgroud)
因为这两个str和unicode是的子类basestring.
要检查类型o是否正好str:
type(o) is str
Run Code Online (Sandbox Code Playgroud)
检查是否o是以下的实例str或子类str:
isinstance(o, str)
Run Code Online (Sandbox Code Playgroud)
以上也为Unicode字符串的工作,如果你更换str使用unicode.
但是,您可能根本不需要进行显式类型检查."鸭子打字"可能适合您的需求.请参阅http://docs.python.org/glossary.html#term-duck-typing.
sev*_*rce 154
在Python 3.x basestring不再可用,因为str唯一的字符串类型(使用Python 2.x的语义unicode).
因此,Python 3.x中的检查只是:
isinstance(obj_to_test, str)
Run Code Online (Sandbox Code Playgroud)
这是在官方转换工具的修复之后2to3:转换basestring为str.
Nic*_*k T 91
如果你想检查不考虑Python版本(2.x vs 3.x),请使用six(PyPI)及其string_types属性:
import six
if isinstance(obj, six.string_types):
print('obj is a string!')
Run Code Online (Sandbox Code Playgroud)
在six(一个非常轻量级的单个文件模块),它只是在做这个:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str
else:
string_types = basestring
Run Code Online (Sandbox Code Playgroud)
小智 18
我发现这个更多pythonic:
if type(aObject) is str:
#do your stuff here
pass
Run Code Online (Sandbox Code Playgroud)
因为类型对象是单例,所以可以用来将对象与str类型进行比较
cla*_*cke 12
如果想远离明确的类型检查远(有有充足的理由远离它),可能是串协议,以检查是最安全的一部分:
str(maybe_string) == maybe_string
Run Code Online (Sandbox Code Playgroud)
它不会通过迭代或迭代循环,它不会调用列表的串一个字符串,它正确地检测弦乐器的弦.
当然有缺点.例如,str(maybe_string)可能是一个繁重的计算.通常,答案取决于它.
小智 11
为了检查你的变量是否适合你:
s='Hello World'
if isinstance(s,str):
#do something here,
Run Code Online (Sandbox Code Playgroud)
isistance的输出将为您提供布尔值True或False,以便您可以相应地进行调整.您可以通过最初使用来检查值的预期首字母缩写:type(s)这将返回键入'str',以便您可以在isistance函数中使用它.
很简单,使用下面的代码(我们假设提到的对象是obj)-
if type(obj) == str:
print('It is a string')
else:
print('It is not a string.')
Run Code Online (Sandbox Code Playgroud)
我可能会像其他人提到的那样以鸭子打字的方式处理这个问题.我怎么知道字符串真的是一个字符串?好吧,显然通过将其转换为字符串!
def myfunc(word):
word = unicode(word)
...
Run Code Online (Sandbox Code Playgroud)
如果arg已经是字符串或unicode类型,则real_word将保持其值不被修改.如果传递的对象实现了一个__unicode__方法,那么该方法用于获取其unicode表示.如果传递的对象不能用作字符串,则unicode内置引发异常.