如何查找关键字的字母值

时间:2015-03-03 11:55:10

标签: python

我目前正在尝试制作一个允许我使用关键字对单词进行加密和解密的程序,我被告知使用字母值从另一个单词中添加字母值我知道我需要使用{{1 }}或ord但我对使用它不是很有信心,因为我是编程的初学者,但是我不知道如何做到这一点并且非常感激,如果有人可以向我解释一下实例

2 个答案:

答案 0 :(得分:0)

s = "foo!#bar"


enc_key = "key"
# get sum of ord's  of letters in key modulo 256
sm_ords= sum(map(ord,enc_key)) % 256

  # add sum of ord's in encryption letter in key to ord of each char in s and use chr to create a new char 
enc = "".join(chr((sm_ords + ord(ch))) for ch in s)

# reverse the encryption using - ord
dec = "".join(chr((ord(ch) - sm_ords)) for ch in enc)


print(enc)
print(dec)

¯¸¸jl«ª»
foo!#bar

答案 1 :(得分:0)

此代码通过将每个关键字字母的值添加到要加密的字符串中的每个字符来加密/解密字符串。

def encryptfunction():
    result = ""
    addedup = 0
    for letter in wordtoencrypt:
        for letter2 in keyword:
            addedup = addedup + ord(letter2)
        result = result + chr(ord(letter) + addedup)
    return result

def decryptfunction():    
    result = ""
    addedup = 0
    for letter in wordtoencrypt:
        for letter2 in keyword:
            addedup = addedup + ord(letter2)
        result = result + chr(ord(letter) - addedup)
    return result

wordtoencrypt = input("Enter the word to encrypt:")
keyword = input("Enter the keyword:")
encrypt = int(input("encrypt(1) or decrypt(0)"))

if encrypt == 1:
    print(encryptfunction())
else:
    print(decryptfunction())