我想通过在每个char的ascii中添加一个字符串来将字符串编码为新字符串,并存储到新字符串,但是我收到一些错误, 我的代码是这样的:
def encode(data):
new_data = ''
try:
for c in data:
new_data += chr(ord(c) + 1)
except Exception as e:
print "encode error(%s)" % e
return new_data
我得到了例外:chr()arg不在范围(256)中,有人可以帮助我吗?
答案 0 :(得分:0)
def increment_ascii(string):
if not isinstance(string, str):
raise TypeError("Expected <class 'str'>, got {}".format(type(string)))
ret = list()
for char in string:
try:
char = chr(ord(char) + 1)
except ValueError:
pass
ret.append(char)
return ''.join(ret)
答案 1 :(得分:0)
我解决了这样的问题,只要判断ascii是否为255:
def encode(data):
data = bytearray(data)
try:
for i in range(len(data)):
if data[i] < 255:
data[i] = data[i] + 1
elif data[i] == 255:
data[i] = 0
else:
print "data encode not right(%d)" % data[i]
except Exception as e:
print "encode error(%s)" % e
return data
谢谢你们所有人。
答案 2 :(得分:0)
我看到你已经回答了这个问题,但是因为我输入了所有内容......
你问不可能:一个字节存储256个可能的值,你偶尔会需要第257个。 (注意&#34;字节&#34; 不与&#34; ASCII&#34;相同。)
更具体地说,您不能用任意其他字节替换有效ASCII字符串(或许多其他字符串)的字节,并期望结果仍然是原始编码中的有效字符串。正如您所发现的,即使添加1也足够随意。
(因为你提到C:是的,你可以向任何char
添加1(实际上是一个字节).C偶尔会实现producing the wrong answer。这是一个错误,如果不是在C中,至少在你的C程序中。)
因此,请考虑您的两个不兼容的目标 - 将字符串加密为不可读的二进制blob,而将有效字符串转换为另一个也是有效的字符串---并确定哪一个对您更重要。
这是我建议将任何字节--- ASCII或非ASCII转换为其他字节。他们的关键是旋转 1,而不是添加1.最后一个值必须映射到某些东西,在这种情况下通常的答案是&#34;环绕&# 34;回到0。
如果你真的想坚持使用ASCII(只是256字节值的下半部分),你可能只想改组可打印的字符。在这种情况下,您可能希望执行类似的轮播,但仅限于0x20
之前但不包括0x7f
的值。人们对&#34;可打印&#34;的定义不尽相同,但这将包括所有常用的字母,数字和标点符号,同时单独留下标签(0x09
)和删除(0x7f
)。
下面的示例代码像任何其他可打印字符一样旋转空格(0x20
)。你可以通过声明&#34; printables&#34;来保持空间完好无损。在空格字符后面开始:将p_start
设置为0x21
而不是0x20
。
以下是一个例子:
from __future__ import print_function
import sys
def rotated(s, rotation=1):
"""
Returns a new string with all characters in the given string
rotated by rotation (1, by default).
The result might or might not be a valid string, depending on the
encoding in use.
"""
old_ords = [ord(char) for char in s]
new_ords = [(ordinal + rotation) % 256 for ordinal in old_ords]
new_string = "".join(chr(new_ordinal) for new_ordinal in new_ords)
return new_string
def ascii_rotated(s, rotation=1):
"""
Returns a new string with all "printable" characters in the given
ASCII string rotated by rotation (1, by default).
Spaces (0x20) are considered printable; tabs (0x09) and deletes (0x7f)
are not.
"""
p_start = 0x20 # Space
p_end = 0x7f # Delete
p_span = p_end - p_start
old_ords = [ord(char) for char in s]
new_ords = []
for ordinal in old_ords:
if (p_start <= ordinal < p_end):
new_ordinal = p_start + ((ordinal - p_start + rotation) % p_span)
else:
new_ordinal = ordinal
new_ords.append(new_ordinal)
new_string = "".join(chr(new_ordinal) for new_ordinal in new_ords)
return new_string
def main():
args = sys.argv[1:]
if args:
for arg in sys.argv[1:]:
print(rotated(arg))
print(ascii_rotated(arg))
else:
# Demonstrate rotation of all 256 possible bytes.
# (Redirect this to a file if your terminal can't handle it.)
all_bytes = range(0x100)
all_bytes_as_str = "".join(chr(b) for b in all_bytes)
print(all_bytes_as_str)
print(rotated(all_bytes_as_str))
print(ascii_rotated(all_bytes_as_str))
return
if "__main__" == __name__:
main()