什么看起来像一个str,就像一个str,但不是一个str?

时间:2015-01-14 11:33:41

标签: python python-2.7

我遇到的情况是从外部函数返回var,该函数从API POST请求中获取变量。在这种情况下,我已经把它变成了'hello world'。

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

控制台:

hello world True
hello world False

什么行为像str但不是<?p?


另一种情况,连接工作:

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

2 个答案:

答案 0 :(得分:4)

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

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

> isinstance(u'foo', basestring)
True

答案 1 :(得分:1)

有许多类似字符串的类型,可能是bytearrayunicode

>>> 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'>