使用重音符号将 utf-8 编码为 base64

发布于 2024-08-14 18:19:31 字数 433 浏览 4 评论 0原文

我有一些这样的数据:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋风の叶未落 2024-08-21 18:19:31
base64.b64encode("Hi, %s! Your code is %s" % (data[0].decode('utf8').encode('latin1'), data[0]))
base64.b64encode("Hi, %s! Your code is %s" % (data[0].decode('utf8').encode('latin1'), data[0]))
薯片软お妹 2024-08-21 18:19:31

首先确保您不会对编码等感到困惑。例如,请阅读

然后请注意,主要问题不在于 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.

掩于岁月 2024-08-21 18:19:31

这似乎有效:

...

data = data2
base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
# => 'SGksIERlc2lyw6khIFlvdXIgY29kZSBpcyBEZXNpcsOp'

# I can't test the XMLRPC parts, so this is just a hint ..
for_the_wire = base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
latin_1_encoded = for_the_wire.encode('latin-1')

# send latin_1_encoded over the wire ..

一些 python (2.X) unicode 读物:

This seem to work:

...

data = data2
base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
# => 'SGksIERlc2lyw6khIFlvdXIgY29kZSBpcyBEZXNpcsOp'

# I can't test the XMLRPC parts, so this is just a hint ..
for_the_wire = base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
latin_1_encoded = for_the_wire.encode('latin-1')

# send latin_1_encoded over the wire ..

Some python (2.X) unicode readings:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文