将带有文本的变量转换为带数字的变量

时间:2017-03-03 00:53:21

标签: python-3.x

在Python 3中,我试图编写一个能够为你编码和解码短语或句子的小程序。  问题出在这里:我对python仍然很陌生,需要一些帮助。 我希望程序将字母短语转换为数字流,并将其与用户输入的密钥相乘。然后要对短语进行解码,数字将被键分割并转换回字母。

TL; DR 我想将变量中列出的字母(例如:Message = hello hi)更改为数字(A = 1,B = 2等,(8,5,12,12,15_8,9)),然后才能更改它回来了。

这是迄今为止的全部内容,因此您可以稍微评估我的技能水平:

mainScene.addEventHandler(KeyEvent.KEY_RELEASED, handler);

关于我应该怎么做的一点解释会很好。 我这样做是为了学习,所以请解释任何解决方案!

2 个答案:

答案 0 :(得分:1)

从亚当提出的建议中引出一些关于你如何去做的代码。 delta = ord('A') - 1用于偏移ascii值,以便'A'从1开始。请注意'a'的值为33.请查看由Adam链接的ascii表以供参考。

def encode(text, key):
    delta = ord('A') - 1
    return ', '.join(str((ord(c) - delta) * key) for c in text)

def decode(ords, key):
    delta = ord('A') - 1
    return ''.join(chr(o // key + delta) for o in ords)

def main():
    while True:
        coding = input('Encoding or Decoding? E/D: ').lower()
        if coding == "e":
            key = int(input('Enter a number as your key: '))
            text = input('Enter a message to encode: ')
            print(encode(text, key))
        elif coding == "d":
            key = int(input('Enter your key: '))
            text = map(int, input('Enter a message to decode: ').split(', '))
            print(decode(text, key))
        else:
            break
        print()
# Output
>>> main()
Encoding or Decoding? E/D: e
Enter a number as your key: 1
Enter a message to encode: Hello World!
8, 37, 44, 44, 47, -32, 23, 47, 50, 44, 36, -31

Encoding or Decoding? E/D: d
Enter your key: 1
Enter a message to decode: 8, 37, 44, 44, 47, -32, 23, 47, 50, 44, 36, -31
Hello World!

Encoding or Decoding? E/D: 
>>> 

<强>加成:

如果您愿意,您也可以使用短语作为密钥。

def conv_key(inp):
    if inp.isdigit():
        return int(inp)
    return sum(ord(c) for c in inp)

然后将int强制转换为conv_key,如此

key = conv_key(input('Enter a number or phrase as your key: '))
key = conv_key(input('Enter your key: '))

>>> main()
Encoding or Decoding? E/D: e
Enter a number or phrase as your key: python
Enter a message to encode: Hello World!
5392, 24938, 29656, 29656, 31678, -21568, 15502, 31678, 33700, 29656, 24264, -20894

Encoding or Decoding? E/D: d
Enter your key: python
Enter a message to decode: 5392, 24938, 29656, 29656, 31678, -21568, 15502, 31678, 33700, 29656, 24264, -20894
Hello World!

答案 1 :(得分:0)

您可以使用返回ASCII代码的ord(character_here)使用字符的ASCII值,并使用chr(ascii_code)返回字符。 - 这是供参考的ASCII表 - http://www.jimprice.com/ascii-0-127.gif

http://love-python.blogspot.co.uk/2008/04/convert-text-to-ascii-and-ascii-to-text.html