本文目錄一覽:
求python 凱撒密碼 加碼和解碼
輸入:CAT
輸出:DBU
import string
def caesar_shift(s):
# Write your code here
# To print results to the standard output you can use print
# Example: print “Hello world!”
table = string.maketrans(string.ascii_uppercase, string.ascii_uppercase[1:] + string.ascii_uppercase[:1]) #1表示加密時右移1位
print s.translate(table)
caesar_shift(“CAT”)
str.maketrans()是創建一個字符翻譯表,而str.translate()就是根據這個翻譯表,翻譯這個字符串。(比按asc碼求模更簡潔)
string.translate(table [, deletechars])
string.maketrans(intab, outtal)
如果解決了您的問題請採納!
如果未解決請繼續追問
如何用python編寫凱撒密碼 ?
凱撒密碼是對字母表整體進行偏移的一種變換加密。因此,建立一個字母表,對明文中每個字母,在這個字母表中偏移固定的長度即可得到對應的密文字母。
最基本的實現如下:
def caesarcipher(s: str,rot: int=3) -str:
_ = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
encode = ”
i = 0
for c in s:
try:
encode += _[(_.index(c.upper()) + rot) % len(_)]
except (Exception,) as e:
encode += c
return encode
print(caesarcipher(‘hellow’))
print(caesarcipher(‘KHOORZ’, -3))
如果要求解密後保持大小寫,那麼,字母表_還需要包含所有小寫字母並且index時不對c做upper處理.
同樣的,也可以在字母表中追加數字,各種符號,空格等.
python編寫凱撒密碼!!!求大神幫助!!!
exec(‘moveLength = int(raw_input(“Input raw_input amount, expect a int number”))\nprint “”.join([dict(zip(list(“abcdefghijklmnopqrstuvwxyz”), [list(“abcdefghijklmnopqrstuvwxyz”)[(i + moveLength) % 26] for i in range(26)]))[x] for x in list(raw_input(“String to change:”))])’)
樓主分沒給夠, 所以只能看到這樣的代碼嘍……o((≧▽≦o) ……
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/257958.html