【问题标题】:Moving a string forward in the alphabet?在字母表中向前移动一个字符串?
【发布时间】:2014-10-25 11:59:16
【问题描述】:

我被要求创建一个加密输入的程序作为挑战。我已经研究过创建一个程序,但没有太多关于如何去做的事情。看起来它不应该太复杂,但我的课程中没有教过它。我也读过这篇文章Get character position in alphabet,但运气不佳!到目前为止我有这个:

import sys
import os
import time
import string
def Cryption():
    ####################
    encrypt = 'encrypt'
    decrypt = 'decrypt'
    ####################
    s = raw_input("Would you like to encrypt or decrypt? Enter your answer")
    if encrypt in s:
        print("Loading encryption sector...")
        time.sleep(2)
        enc = raw_input("Please input the string you would like to encrypt")
        print ("Your decrypted word is: " + enc)
    if decrypt in s:
        print("Loading decryption sector...")
        time.sleep(2)
        dec = raw_input("Please input the string you would like to decrypt")
    else:
        print("Your input was invalid, please re-enter your choice!")
        r = raw_input("Press enter to restart your program")
        Cryption()
Cryption()

我在想如果我将输入添加到每个字母值上,然后重新打印产品。我将使用哪些函数将 5 添加到字母表的顺序中?排序()?如果是这样,有人可以指出如何使用它的方向吗?提前致谢!

【问题讨论】:

  • 你不能添加一个 int 和一个字符串
  • 我已经改变了,也谢谢你的提示。我会使用 ord() 然后使用另一个函数来移动字母吗?
  • 我会使用一个字母字典,使用模数进行移位
  • 模数是像pygame这样的单独的东西吗?如果是这样,我有一个问题,因为它需要在学校展示,我们不能下载单独的东西! D:这是一个很大的限制
  • 取模运算符%

标签: python


【解决方案1】:
import string


def encrypt_s(shift):
    lower = string.ascii_lowercase
    # shift forward current index of each character + the shift
    dict_map = {k:lower[(lower.index(k)+shift)%26] for k in lower}
    return dict_map

def decrypt_s(shift):
    lower = string.ascii_lowercase
    # shift forward current index of each character - the shift to get original string
    dict_map = {k:lower[(lower.index(k)-shift)%26] for k in lower}
    return dict_map


def Cryption():

    ####################
    encrypt = 'encrypt'
    decrypt = 'decrypt'
    ####################
    s = raw_input("Would you like to encrypt or decrypt? Enter your answer")
    if encrypt in s:
        print("Loading encryption sector...")
        time.sleep(2)
        enc = raw_input("Please input the string you would like to encrypt").lower()
        enc_s = encrypt_s(5)
        enc = "".join([enc_s[char] if char in enc_s else char for char in enc])
        print ("Your encrypted word is: ",enc)
    elif decrypt in s:
        print("Loading decryption sector...")
        time.sleep(2)
        dec = raw_input("Please input the string you would like to decrypt").lower()
        dec_s = decrypt_s(5)
        dec = "".join([dec_s[char] if char in dec_s else char for char in dec])
        print ("Your decrypted word is: ",dec)
    else:
        print("Your input was invalid, please re-enter your choice!")

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2019-09-29
    • 2016-01-01
    • 2020-08-11
    • 2016-01-10
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多