如何使用Python反转字符串中每个字符的位数

2024-04-23 09:54:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找到一种使用python反转字符串中每个字符的位的方法。你知道吗

例如,如果我的第一个字符是J,那么这是ASCII 0x4a0b01001010,因此将反转为0x520b01010010。如果我的第二个字符是K,那么这是0b01001011,因此可以反转为0xd20b11010010,依此类推

最终结果应作为string返回。你知道吗

速度是我在这里的第一要务,所以我正在寻找一个快速的方法来实现这一点。你知道吗


Tags: 方法字符串stringascii字符速度要务
3条回答

接受了建议后,我的解决方案如下:

# Pre-populate a look-up array with bit-reversed integers from 0 to 255
bytearray = []
for i in range(0, 256):
    bytearray.append(int('{:08b}'.format(i)[::-1], 2))

# Reverses the bits of each character in the input string and returns the result
# as a string
def revstr(string):
    return ''.join([chr(bytearray[ord(a)]) for a in list(string)])

print "JK".encode("hex")         # 0x4a4b
print revstr("JK").encode("hex") # 0x52d2

如果您的目标是速度,并且您使用的是ASCII,因此您只有256个8位值要处理,请事先计算反向字节值并将它们放入bytearray,然后通过索引到bytearray中来查找它们。你知道吗

 a=bin(ord("a"))
'0b'+a[::-1][0:len(a)-2]

如果要对大量字符执行此操作,那么只有256个ascii字符。将反转的字符串存储在hashmap中,并在hashmap上进行查找。这些查找的时间复杂度是O(1),但是有一个固定的设置时间。你知道吗

相关问题 更多 >