假设你有一个字符串:
mystring = "Welcome to the InterStar cafe, serving you since 2412!"
我正在寻找一种将字符串转换为数字的方法,就像这样:
encoded_string = number_encode(mystring)
print(encoded_string)
08713091353153848093820430298
..that您可以将其转换回原始字符串。
decoded_string = number_decode(encoded_string)
print(decoded_string)
"Welcome to the InterStar cafe, serving you since 2412!"
它不一定是密码安全的,但无论它运行在哪台计算机上,它都必须为相同的字符串提供相同的数字。
发布于 2019-03-29 06:28:13
将其encode
为固定编码的bytes
,然后使用int.from_bytes
将bytes
转换为int
。相反的操作是在生成的int
上调用.to_bytes
,然后用decode
返回str
mystring = "Welcome to the InterStar cafe, serving you since 2412!"
mybytes = mystring.encode('utf-8')
myint = int.from_bytes(mybytes, 'little')
print(myint)
recoveredbytes = myint.to_bytes((myint.bit_length() + 7) // 8, 'little')
recoveredstring = recoveredbytes.decode('utf-8')
print(recoveredstring)
这有一个缺陷,那就是如果字符串以NUL
字符('\0'
/\x00'
)结尾,您将丢失它们(切换到'big'
字节顺序将从前面丢失它们)。如果这是一个问题,你总是可以显式地填充一个'\x01'
,并在解码端删除它,这样就没有尾随的0可丢失:
mystring = "Welcome to the InterStar cafe, serving you since 2412!"
mybytes = mystring.encode('utf-8') + b'\x01' # Pad with 1 to preserve trailing zeroes
myint = int.from_bytes(mybytes, 'little')
print(myint)
recoveredbytes = myint.to_bytes((myint.bit_length() + 7) // 8, 'little')
recoveredstring = recoveredbytes[:-1].decode('utf-8') # Strip pad before decoding
print(recoveredstring)
发布于 2019-03-29 06:28:07
如果您只是想让某个字符串变得不可读,您可以使用base64
、base64.b64encode(s, altchars=None)
和base64.b64decode(s, altchars=None, validate=False)
考虑到它需要类似字节的对象,所以字符串应该以b"I am a bytes-like string":
开头
>>> import base64
>>> coded = base64.b64encode(b"Welcome to the InterStar cafe, serving you since 2412!")
>>> print(coded)
b'V2VsY29tZSB0byB0aGUgSW50ZXJTdGFyIGNhZmUsIHNlcnZpbmcgeW91IHNpbmNlIDI0MTIh'
>>> print(base64.b64decode(coded))
b"Welcome to the InterStar cafe, serving you since 2412!"
如果您已经有字符串,可以使用str.encode('utf-8')
对其进行转换
>>> myString = "Welcome to the InterStar cafe, serving you since 2412!"
>>> bString = myString.encode('utf-8')
>>> print(bString)
b'Welcome to the InterStar cafe, serving you since 2412!'
>>> print(bString.decode())
'Welcome to the InterStar cafe, serving you since 2412!'
如果您确实需要将字符串仅转换为数字,则必须使用@ShadowRanger's answer。
https://stackoverflow.com/questions/55407713
复制相似问题