简体   繁体   English

将 utf-8 字符串转换为 base64

[英]Convert utf-8 string to base64

I converted base64 str1= eyJlbXBsb3llciI6IntcIm5hbWVcIjpcInVzZXJzX2VtcGxveWVyXCIsXCJhcmdzXCI6XCIxMDQ5NTgxNjI4MzdcIn0ifQ我转换了 base64 str1= eyJlbXBsb3llciI6IntcIm5hbWVcIjpcInVzZXJzX2VtcGxveWVyXCIsXCJhcmdzXCI6XCIxMDQ5NTgxNjI4MzdcIn0ifQ

to str2= {"employer":"{\\"name\\":\\"users_employer\\",\\"args\\":\\"104958162837\\"}"} to str2= {"employer":"{\\"name\\":\\"users_employer\\",\\"args\\":\\"104958162837\\"}"}

with help of http://www.online-decoder.com/ruhttp://www.online-decoder.com/ru 的帮助下

I want to convert str2 to str1 with help of python.我想在python的帮助下将str2转换为str1。 My code:我的代码:

import base64

data = """{"employer":"{"name":"users_employer","args":"104958162837"}"}"""
encoded_bytes = base64.b64encode(data.encode("utf-8"))
encoded_str = str(encoded_bytes, "utf-8")
print(encoded_str)

The code prints str3=代码打印 str3=

eyJlbXBsb3llciI6InsibmFtZSI6InVzZXJzX2VtcGxveWVyIiwiYXJncyI6IjEwNDk1ODE2MjgzNyJ9In0=

What should I change in code to print str1 instead of str3 ?我应该在代码中更改什么来打印str1而不是str3

I tried我试过

{"employer":"{\"name\":\"users_employer\",\"args\":\"104958162837\"}"}

and

{"employer":"{"name":"users_employer","args":"104958162837"}"}

but result is the same但结果是一样的

The results you want are just base64.b64decode(str1 + "==") .你想要的结果只是base64.b64decode(str1 + "==") See this post for more information on the padding.有关填充的更多信息,请参阅此帖子

The problem is that \\" is a python escape sequence for the single character " .问题是\\"是单个字符"的python转义序列。 The fix is to keep the backslashes and use a raw string (note the "r" at the front).解决方法是保留反斜杠并使用原始字符串(注意前面的“r”)。

data = r"""{"employer":"{\"name\":\"users_employer\",\"args\":\"104958162837\"}"}"""

This will be the original string, except that python pads base64 numbers to 4 character multiples with the "=" sign.这将是原始字符串,除了 python 使用“=”符号将 base64 数字填充为 4 个字符的倍数。 Strip the padding and you have the original.去掉填充,你就有了原来的。

import base64

str1 = "eyJlbXBsb3llciI6IntcIm5hbWVcIjpcInVzZXJzX2VtcGxveWVyXCIsXCJhcmdzXCI6XCIxMDQ5NTgxNjI4MzdcIn0ifQ"
str1_decoded = base64.b64decode(str1 + "="*divmod(len(str1),4)[1]).decode("ascii")
print("str1", str1_decoded)

data = r"""{"employer":"{\"name\":\"users_employer\",\"args\":\"104958162837\"}"}"""
encoded_bytes = base64.b64encode(data.encode("utf-8"))
encoded_str = str(encoded_bytes.rstrip(b"="), "utf-8")
print("my encoded", encoded_str)
print("same?", str1 == encoded_str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM