How Does One Encode And Decode A String With Python For Use In A Url?
Solution 1:
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:
input: 12234_1_Hello'World_34433_22acb_4554344_accCC44
encoded: MTIyMzRfMV9IZWxsbydXb3JsZF8zNDQzM18yMmFjYl80NTU0MzQ0X2FjY0NDNDQ=
decoded: 12234_1_Hello'World_34433_22acb_4554344_accCC44
Solution 2:
Are you looking to encrypt the string or encode it to remove illegal characters for urls?
If the latter, you can use urllib.quote
:
>>>quoted = urllib.quote("12234_1_Hello'World_34433_22acb_4554344_accCC44")>>>quoted
'12234_1_Hello%27World_34433_22acb_4554344_accCC44'
>>>urllib.unquote(quoted)
"12234_1_Hello'World_34433_22acb_4554344_accCC44"
Solution 3:
Are you after encryption, compression, or just urlencoding? The string can be passed after urlencoding, but that will not make it smaller as in your example. Compression might shrink it, but you would still need to urlencode the result.
Do you actually need to hide the string data from the viewer (e.g. sensitive data, should not be viewable by someone reading the URL over your shoulder)?
Solution 4:
To make it really short -> just insert a row into the database. Store something like a list of (id auto_increment, url)
tuples. Then you can base64
encode the id to get a "proxy url". Decode it by decoding the id and looking up the proper url in the database. Or if you don't mind the identifiers looking sequential, just use the numbers.
Solution 5:
The base64 module provides encoding and decoding for a string to and from different bases, since python 2.4.
In you example, you would do the following:
importbase64string_b= base64.b64encode(string_a)
string_a = base64.b64decode(string_b)
For full API: http://docs.python.org/library/base64.html
Post a Comment for "How Does One Encode And Decode A String With Python For Use In A Url?"