什么看起来像 str,行为像 str,但不是 str?

What looks like a str, acts like a str, but isn't a str?

我有这样一种情况,从 API POST 请求中获取变量的外部函数返回 var。在这种情况下,我做到了 'hello world'.

a='hello world'
print a, isinstance(a, str)
print var, isinstance(var, str)

控制台:

hello world True
hello world False

什么行为类似于 str 而不是?


另一种情况,连接有效:

a = 'hello world'
var += '!'
print a, isinstance(a, str)
print var, isinstance(var, str)

控制台:

hello world True
hello world! False

询问类型

print type(var)

Traceback (most recent call last):
  File "/home/will/env/feed/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/will/env/feed/local/lib/python2.7/site-packages/django/views/generic/base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/will/env/feed/local/lib/python2.7/site-packages/django/utils/decorators.py", line 29, in _wrapper
    return bound_func(*args, **kwargs)
  File "/home/will/env/feed/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/will/env/feed/local/lib/python2.7/site-packages/django/utils/decorators.py", line 25, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/home/will/local/feed/src/fAPI/base.py", line 178, in dispatch
    return self.post()
  File "/home/will/local/feed/src/ublog/api.py", line 91, in post
    message = self.get_BODY_safe('message', 1)
  File "/home/will/local/feed/src/fAPI/base.py", line 141, in get_BODY_safe
    print type(var)
TypeError: 'int' object is not callable

有很多类似字符串的类型,可能是bytearray或者unicode

>>> t = str('abcde')
>>> isinstance(t, str)
True
>>> isinstance(t, bytearray)
False
>>> isinstance(t, unicode)
False
>>> t = bytearray('abcde')
>>> isinstance(t, str)
False
>>> isinstance(t, unicode)
False
>>> isinstance(t, bytearray)
True

如果您想知道您处理的是哪种类型,请使用函数 type

>>> t = bytearray('abcde')
>>> type(t)
<type 'bytearray'>

您已经发现该变量实际上是 unicode。 Python 2 有一个结合了这两种类型的基本类型,您可以在 isinstance 中使用它:basestring.

>>> isinstance('foo', basestring)
True

> isinstance(u'foo', basestring)
True