如何将ASCII(不是单个字符,完整句子)转换为字符串

时间:2017-11-06 03:53:31

标签: python-2.7 ascii

我有一个名为'encode(string_argument)'的方法,它将字符串(句子)转换为ascii并将其反转。我必须编写解码字符串的方法。

代码:

str1 = 'This is sample text'

def encode(str1):
    encoded_str = ''
    for i in str1:
        encoded_str += str(ord(i))
    return encoded_str[::-1]

def decode(encoded_str):
    rev_encoded_str = encoded_str[::-1]
    # Incomplete

encoded_str = encode(str1)
decode(encoded_str)

编码()的输入: 这是示例文本

来自encode()的输出: 6110211016112310180121190179511235115012351150140148

decode()的输入: 6110211016112310180121190179511235115012351150140148

decode()的输出: 这是示例文本

提前致谢。

1 个答案:

答案 0 :(得分:0)

终于得到了解决方案:

def encode(str1):
    encoded_str = ''
    for i in str1:
        encoded_str += str(ord(i))
    return encoded_str[::-1]

def decode(encoded_str):
    reverse_string = encoded_str[::-1]
    temp_array = convert_to_possible_string_ascii(reverse_string)
    final_decoded_string = ""
    for x in temp_array:
        # print(str(chr(int(x)))+": "+x)
        final_decoded_string = final_decoded_string + str(chr(int(x)))
    print(final_decoded_string)
    return final_decoded_string

def convert_to_possible_string_ascii(str_array):
    temp_array = []
    temp_char = ""
    counter = 0
    for current_char in range(0, len(str_array), 1):
        temp_char = temp_char+str_array[current_char]
        counter = counter+1
        if counter==1:
            temp_var = is_valid_string_ascii(temp_char)
            if temp_var:
                temp_array.append(temp_char)
                counter = 0
                temp_char = ""
        elif counter==2:
            temp_var = is_valid_string_ascii(temp_char)
            if temp_var:
                temp_array.append(temp_char)
                counter = 0
                temp_char = ""
        elif counter==3:
            temp_var = is_valid_string_ascii(temp_char)
            if temp_var:
                temp_array.append(temp_char)
                counter = 0
                temp_char = ""          
    return temp_array


def is_valid_string_ascii(ascii_value):
    valid_list = list(range(65, 91)) + list(range(97, 123)) +[32]
    boolean_var = False
    if int(ascii_value) in valid_list:
        boolean_var = True
    return boolean_var

str1 = 'This is sample text'
encoded_str = encode(str1)
decode(encoded_str)