首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python中将文本字符串编码为数字?

如何在Python中将文本字符串编码为数字?
EN

Stack Overflow用户
提问于 2019-03-29 06:20:33
回答 2查看 4.9K关注 0票数 4

假设你有一个字符串:

代码语言:javascript
复制
mystring = "Welcome to the InterStar cafe, serving you since 2412!"

我正在寻找一种将字符串转换为数字的方法,就像这样:

代码语言:javascript
复制
encoded_string = number_encode(mystring)

print(encoded_string)

08713091353153848093820430298

..that您可以将其转换回原始字符串。

代码语言:javascript
复制
decoded_string = number_decode(encoded_string)

print(decoded_string)

"Welcome to the InterStar cafe, serving you since 2412!"

它不一定是密码安全的,但无论它运行在哪台计算机上,它都必须为相同的字符串提供相同的数字。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-29 06:28:13

将其encode为固定编码的bytes,然后使用int.from_bytesbytes转换为int。相反的操作是在生成的int上调用.to_bytes,然后用decode返回str

代码语言:javascript
复制
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)

Try it online!

这有一个缺陷,那就是如果字符串以NUL字符('\0'/\x00')结尾,您将丢失它们(切换到'big'字节顺序将从前面丢失它们)。如果这是一个问题,你总是可以显式地填充一个'\x01',并在解码端删除它,这样就没有尾随的0可丢失:

代码语言:javascript
复制
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)
票数 7
EN

Stack Overflow用户

发布于 2019-03-29 06:28:07

如果您只是想让某个字符串变得不可读,您可以使用base64base64.b64encode(s, altchars=None)base64.b64decode(s, altchars=None, validate=False)

考虑到它需要类似字节的对象,所以字符串应该以b"I am a bytes-like string":开头

代码语言:javascript
复制
>>> 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')对其进行转换

代码语言:javascript
复制
>>> 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55407713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档