gpt4 book ai didi

python - 无法在 Python 中引用 unicode 字符串

转载 作者:行者123 更新时间:2023-12-01 04:11:34 24 4
gpt4 key购买 nike

我有一个包含非 ASCII 字符的 unicode 对象 userId。我尝试使用 xml.sax.saxutils 中的函数引用此字符串以将其用作 XML 属性:

quoteattr(userId)

这给了我这个错误:

'ascii' codec can't encode character u'\xa0'

我想我已经阅读了网上所有的python unicode信息,包括https://docs.python.org/2/howto/unicode.html#the-unicode-type

但是我还是不明白问题出在哪里。我已经有一个 unicode 对象。我不关心编码。编码是当我想从 unicode 转换为字节数组或反之亦然时。我从来没有在我的代码中处理原始字节数组。

基本上,最大的问题是,如果我给它一个 unicode 对象并期望 unicode 对象,为什么 quoteattr 要使用 ascii 编码来编码某些内容回来了?

我通过执行userId.encode('ascii', 'ignore')解决了这个问题,但这显然会丢弃任何非ascii字符。

如何引用我的 unicode 字符串?

使用 Google App Engine 通过 userId = ndb.StringProperty() 为该变量赋值。

最佳答案

一旦您提到 Google App Engine,我就使用了一个使用它的示例:

from xml.sax.saxutils import quoteattr
from google.appengine.ext import ndb
from google.appengine.ext.ndb.model import Model


class Foo(Model):
bar=ndb.StringProperty()


foo=Foo(bar='''barç"á<&' >


''')

print type(foo.bar)

print quoteattr(foo.bar)

这里的问题是 foo.bar 是一个 str,所以你会遇到编码问题。有两种解决方法:

1) 使用 u 前缀。所以

foo=Foo(bar='''barç"á<&'  >


''')

成为

foo=Foo(bar=u'''barç"á<&'  >


''')

2) 在脚本的开头添加两行:

# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

我更喜欢第二种方法。我将 Pycharm 配置为在每个新创建的 py 文件中添加此行。

请注意,此问题仅在使用文字设置模型属性时发生。 Webapp2 和 GAE 使用的大多数框架将请求数据转换为 unicode,因此您不必担心编码/解码。

关于python - 无法在 Python 中引用 unicode 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34862132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com