python中的字典类型转化为bytes类型,及base64编码中“”双引号和‘’单引号编码结果不同

import base64
import json
1.
a={"Vod":{"userData":"{}".format("e42e6dedf7a5a3fd19689aeb74bb1605")}}
r=bytes('{}'.format(a),'utf-8')
print(r)   #b"{'Vod': {'userData': 'e42e6dedf7a5a3fd19689aeb74bb1605'}}"

base64.b64encode(r).decode('utf-8')  #'eydWb2QnOiB7J3VzZXJEYXRhJzogJ2U0MmU2ZGVkZjdhNWEzZmQxOTY4OWFlYjc0YmIxNjA1J319'

2.

a={"Vod":{"userData":"{}".format("e42e6dedf7a5a3fd19689aeb74bb1605")}}

base64.b64encode(json.dumps(a).replace(' ','').encode('utf-8')).decode('utf-8')

#'eyJWb2QiOnsidXNlckRhdGEiOiJlNDJlNmRlZGY3YTVhM2ZkMTk2ODlhZWI3NGJiMTYwNSJ9fQ=='

3.

a=b'{"Vod":{"userData":"e42e6dedf7a5a3fd19689aeb74bb1605"}}'

base64.b64encode(a).decode('utf-8')

#'eyJWb2QiOnsidXNlckRhdGEiOiJlNDJlNmRlZGY3YTVhM2ZkMTk2ODlhZWI3NGJiMTYwNSJ9fQ=='

字符串转化为bytes的坑,在转化的时候非常聪明地加了空格,导致三次的base64编码结果不一样,用字符串中的replace将空格替换掉,字符串转化可以用bytes(json.dumps({"lw":"{}".formt("1314")}),'utf-8')或者json.dumps({"lw":"{}".formt("1314")}).encode('utf-8')

字典用str转化成bytes时生成的是单引号,用json.dumps()生成的json格式是双引号

你可能感兴趣的:(字符串转化,python,bytes,str)