Python 搔痒如何处理磅标志?

Python 搔痒如何处理磅标志?,python,scrapy,Python,Scrapy,我不熟悉Python和Scrapy,我正在尝试测试字符串(使用xpath选择器提取)是否包含英镑符号(英国货币-) 在源文件的顶部,我指定了编码: # -*- coding: latin-1 -*- 我正在做这个测试: if '£' in price: ... 但是,我收到一个错误异常。UnicodeDecodeError:“ascii”编解码器无法解码字节0xc2 如果我把测试改为 price = price.encode('utf-8') if '£' in price: ... 它起

我不熟悉Python和Scrapy,我正在尝试测试字符串(使用xpath选择器提取)是否包含英镑符号(英国货币-)

在源文件的顶部,我指定了编码:

# -*- coding: latin-1 -*-
我正在做这个测试:

if '£' in price:
...
但是,我收到一个错误异常。UnicodeDecodeError:“ascii”编解码器无法解码字节0xc2

如果我把测试改为

price = price.encode('utf-8')
if '£' in price:
...
它起作用了。有人能解释一下为什么需要调用price.encode()吗?我知道Scrapy无论如何都会返回unicode字符串。非常感谢

# these have different types:
if some_string in some_unicode_object
这样做相当于写:

# convert the first argument so we can do the `in`
if some_string.decode('ascii') in some_unicode_object
在你的例子中:

if '£' in price:
#  ^string ^unicode
您正在调用
“£”.encode('ascii')
,由于它不是ascii bytestring,因此失败

更好的写作方法是:

if u'£' in price:

或者,你也可以写信。

谢谢,这很有道理