本文介绍了文本字符串到唯一整数方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有把'you'这样的文本字符串转换成

以外的数字的方法

y = tuple('你')对于 y 中的 k:k = ord(k)

一次只转换一个字符?

解决方案

为了将字符串转换为数字(反之亦然),您应该首先始终使用 bytes.由于您使用的是 Python 3,因此字符串实际上是 Unicode 字符串,因此可能包含 ord() 值大于 255 的字符.bytes 但是只有一个字节每个字符;所以你应该总是先在这两种类型之间转换.

所以基本上,您正在寻找一种方法将 bytes 字符串(基本上是字节列表,数字列表 0-255)转换为单个数字,反之亦然.您可以使用 int.to_bytesint.from_bytes:

导入数学def convertToNumber (s):返回 int.from_bytes(s.encode(), 'little')def convertFromNumber (n):返回 n.to_bytes(math.ceil(n.bit_length()/8), 'little').decode()

>>>convertToNumber('foo bar baz')147948829660780569073512294>>>x = _>>>convertFromNumber(x)'foo bar baz'

Is there a method that converts a string of text such as 'you' to a number other than

y = tuple('you')
for k in y:
  k = ord(k)

which only converts one character at a time?

解决方案

In order to convert a string to a number (and the reverse), you should first always work with bytes. Since you are using Python 3, strings are actually Unicode strings and as such may contain characters that have a ord() value higher than 255. bytes however just have a single byte per character; so you should always convert between those two types first.

So basically, you are looking for a way to convert a bytes string (which is basically a list of bytes, a list of numbers 0–255) into a single number, and the inverse. You can use int.to_bytes and int.from_bytes for that:

import math
def convertToNumber (s):
    return int.from_bytes(s.encode(), 'little')

def convertFromNumber (n):
    return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()
>>> convertToNumber('foo bar baz')
147948829660780569073512294
>>> x = _
>>> convertFromNumber(x)
'foo bar baz'

这篇关于文本字符串到唯一整数方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 09:48