使用重音符号将 utf-8 编码为 base64
我有一些这样的数据:
data1 = ['Agos', '30490349304']
data2 = ['Desir\xc3\xa9','9839483948']
我正在使用一个 API,该 API 需要以 base64 编码的数据,所以我所做的是:
data = data1
string = base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
myXMLRPCCall(string)
这与 data1 配合良好。对于 data2,编码正常,但随后 XMLRPC 返回错误,因为它期望(来自 API 文档)仅 ISO-8859-1 (Latin1) 字符。
我的问题是:如何将字符串转换为 Latin1 以便 API 接受它?
I have some data like this:
data1 = ['Agos', '30490349304']
data2 = ['Desir\xc3\xa9','9839483948']
I'm using an API that expects the data encoded in base64, so what I do is:
data = data1
string = base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
myXMLRPCCall(string)
Which works fine with data1. With data2 the encoding goes ok, but then the XMLRPC returns an error, since it expects (from the API docs) only ISO-8859-1 (Latin1) characters.
My question is: how can I transform my string into Latin1 so that the API accepts it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先确保您不会对编码等感到困惑。例如,请阅读此。
然后请注意,主要问题不在于 base64 编码,而在于您尝试将字节字符串(Python 2.x 中的普通字符串)放入 Unicode 字符串中。我相信您可以通过从示例代码的最后一个字符串中删除“u”来解决此问题。
First make sure you're not confused about encodings, etc. Read, for example, this.
Then notice that the main problem isn't with the base64 encoding, but with the fact that you're trying to put byte string (normal string in Python 2.x) inside a Unicode string. I believe you can fix this by removing the "u" from the last string in your example code.
这似乎有效:
一些 python (2.X) unicode 读物:
This seem to work:
Some python (2.X) unicode readings: