将整个ascii字符串转换为int

时间:2020-05-17 07:45:00

标签: python

我希望将类似“ ASDF”的字符串转换为像“ 123456789”这样的数字,然后可以轻松地将其转换回“ ASDF”,我该如何在python 3中执行此操作?

4 个答案:

答案 0 :(得分:3)

您可以使用ord将每个字符转换为其ascii值,并使用f"{1:02d}"将其格式化为相同的长度,并将它们连接在一起。然后,当您想要返回字符串时,请逆向执行此过程。

类似

def to_num(s):
    return int("1" + "".join(map(lambda a: f"{ord(a):03d}", s)))

def to_str(n):
    num = str(n)[1:]
    chunks = [num[i:i+3] for i in range(0, len(num), 3)]
    return "".join(map(lambda a: chr(int(a)), chunks))

答案 1 :(得分:2)

那呢:

int.from_bytes("ASDF".encode('utf-8'), byteorder='big', signed=False)
1095976006

然后返回

import math
(1095976006).to_bytes(math.ceil((1095976006).bit_length() / 8), byteorder = 'big', signed=False).decode('utf-8')
'ASDF'

它使用编码/解码获取Python字符串的utf-8表示形式为字节数组,然后使用from_bytes / to_bytes将其转换为整数。所以它适用于任何字符串。令人惊讶的是,有必要计算字节数才能使用to_bytes。

答案 2 :(得分:0)

只是想出了一种可能的方法,因为我只使用ASCII,所以应该可以:

inp = "ASDF" #Input string
bits = 8     #Amount of bits per character

num = 0      #Just some setup value, this will be our encoded number
numstr = [ord(letter) for letter in inp] #Turns the string into a list containing each of the letters ascii code
for numletter in numstr: #Loop over each letter
    num = (num<<bits)+numletter #First shift the current num stored by 8 [In binary 01010101 becomes 0101010100000000] which makes room for the next character, then adds the new character in

print("Encoded:",num) #Print the encoded number

#num = 1234, not included as we've defined it before with the encoding part
#bits = 8, same reason as above
outp = "" #Another setup value, this will be our decoded string
AND = ((2**bits)-1) #A setup constant, we'll need this later, this is a number of just 1's in binary with the length of 8.
while num>=1: #Loop over each character
     numletter = num&AND #Bitwise AND it with the constant we got earlier, this'll extract the first character in the number
     outp = chr(numletter) + outp #First convert the extracted number to it's character, then add the character to the front of the output
     num = num>>bits #Remove the extracted number and shift it back by 8

print(outp) #Print the decoded string

答案 3 :(得分:-1)

根据定义,金达有问题。根据字符串的长度,您很容易用完int。除非您在字符串表示中表示数字,否则从理论上讲是可能的,但实际上,您将需要在这些int上作为字符串数字起作用的算法。 基本上,如果您只能使用ascii,请使用以26为基的表示形式:

"F"*26^0 + "D"*26^1 + "S" * 26^ 2 and so on

或者您可以只连接字符代码,这也是一个选择,尽管它似乎毫无意义-您并没有真正将字符串隐蔽到数字,只是以另一种方式打印了它的表示形式。

或者,也许您正在谈论将封闭的字符串集映射为整数-然后将您的字符串放入列表中,并将其索引用作匹配的int。