如何使用 Python 对用于 URL 的字符串进行编码和解码? [英] How does one encode and decode a string with Python for use in a URL?
问题描述
我有一个这样的字符串:
I have a string like this:
String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ]
我想加密字符串 A 以在干净的 URL 中使用.像这样:
I would like to encrypt String A to be used in a clean URL. something like this:
String B: [ cYdfkeYss4543423sdfHsaaZ ]
python 中是否有编码 API,给定字符串 A,它返回字符串 B?python中是否有解码API,给定字符串B,它返回字符串A?
Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?
推荐答案
进行编码/解码的一种方法是使用 base64 包,例如:
One way of doing the encode/decode is to use the package base64, for an example:
import base64
import sys
encoded = base64.b64encode(sys.stdin.read())
print encoded
decoded = base64.b64decode(encoded)
print decoded
这是您要找的吗?对于您的特定情况,您会得到:
Is it what you were looking for? With your particular case you get:
输入:12234_1_Hello'World_34433_22acb_4554344_accCC44
input: 12234_1_Hello'World_34433_22acb_4554344_accCC44
编码:MTIyMzRfMV9IZWxsbydXb3JsZF8zNDQzM18yMmFjYl80NTU0MzQ0X2FjY0NDQ=
encoded: MTIyMzRfMV9IZWxsbydXb3JsZF8zNDQzM18yMmFjYl80NTU0MzQ0X2FjY0NDNDQ=
解码:12234_1_Hello'World_34433_22acb_4554344_accCC44
decoded: 12234_1_Hello'World_34433_22acb_4554344_accCC44
这篇关于如何使用 Python 对用于 URL 的字符串进行编码和解码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!