2012-11-03 30 views
3

我想與我的一個好友開玩笑,我們是特殊的代理,但是我們如何才能成爲特殊的代理而沒有絕密消息代碼來相互通信?如何旋轉字符串中的字符來加密郵件

# txt = the secret message to convert! 
# n = number of times to jump from original position of letter in ASCII code 

def spy_code(txt,n): 
    result = '' 
    for i in txt: 
     c = ord(i)+n 
     if ord(i) != c: 
      b = chr(c) 
      result += b 
    print result 

spy_code('abord mission, dont atk teacher!',5) 

祕密消息轉換消息後我們得到了一個行文字......

fgtwi%rnxxnts1%itsy%fyp%yjfhmjw& 

的問題是,我們希望達到這樣的結果:

fgtwi rnxxnts, itsy fyp yjfhmjw! 

考慮只有字母。

只能使用間諜碼來轉換字母,不要轉換空格或特殊符號。

+0

作爲一個線索,它看起來像你只需要如果角色是字母則轉換。字符串模塊中可以找到一串大小寫字母。 '輸入字符串; string.letters' – GP89

+1

我不完全得到負面票:s。這對我來說是一個正確的問題 – jlengrand

+0

@hayden,對不起,'a'是'c',剛剛糾正。 Jlengrand他們就像羊,讓我們加入讓我們beep, – user1768615

回答

2

一個簡單的方法,使用尖端GP89給你。

只需檢查您的當前字符是否在字母列表中;否則只返回它,因爲它是

import string 

vals = string.letters 
def spy_code(txt,n): 
    result = '' 
    for i in txt: 
     if i in vals: 
      c = ord(i)+n 
      if ord(i) != c: 
       b = chr(c) 
       result += b 
     else: 
      result += i 
    print result 

spy_code('abord mission, dont atk teacher!',5) 

回報

fgtwi rnxxnts, itsy fyp yjfhmjw! 
0

我現在這個是舊的,但你可以使用str.isalpha()

s = 'Impending doom approaches!' 
n = 6 
result = '' 

for c in s: 
    result += chr(ord(c) + n) if c.isalpha() else c 

print(result) 
>>> Osvktjotm juus gvvxuginky!