2017-02-25 44 views
0

我希望輸出打印指定Caeser移位的字符串,但我的輸出似乎在輸出內重複輸入。任何幫助將非常感激。發生Caeser Shift Output

# Prompt the user for a string and integer 
string = input('Enter the string to encode: ') 
i = int(input('Enter integer value to use: ')) 

# Create a for loop based on the characters in the string 
# Build a new string of encoded characters based on the given rules 
string= string.upper() 
coded="" 
for y in string: 
    if y in "ABCDEFGHIJKLMNOPQRSTUCWXYZ": 
     num=ord(y) 
     num+=i 
     if num>ord("Z"): 
      num-=26 
     elif num<ord("A"): 
      num+=26 
     coded=coded+chr(num) 
    else: 
     space = string.replace(" ","#") 
     coded=coded+space 


# Display the new string 
print("Your encoded message is:",coded) 
+2

'space = string.replace(「」,「#」)'不會l ook對我來說。 – Kevin

+1

兩個注意事項:你有一個錯字(重複C,你的字母表中應該有V),當我自己嘗試你的程序時,它似乎大多正常工作。你能顯示有問題的輸入和輸出嗎? –

+0

啊,我明白了,當輸入中有非字母時,它就會起作用。 –

回答

2

你的錯誤在space = string.replace(" ","#")

這裏發生的事情是,你得到整個字符串,但使用的字符,也有字母改爲#

爲了解決這個問題,只需刪除space = string.replace(" ","#")和將coded=coded+space更改爲coded=coded+"#"

# Prompt the user for a string and integer 
string = input('Enter the string to encode: ') 
i = int(input('Enter integer value to use: ')) 

# Create a for loop based on the characters in the string 
# Build a new string of encoded characters based on the given rules 
string= string.upper() 
coded="" 
for y in string: 
    if y in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": 
     num=ord(y) 
     num+=i 
     if num>ord("Z"): 
      num-=26 
     elif num<ord("A"): 
      num+=26 
     coded=coded+chr(num) 
    else: 
     coded=coded+"#" 


# Display the new string 
print("Your encoded message is:",coded) 
+0

另外,在「ABCDEFGHIJKLMNOPQRSTUCWXYZ」中將重複C更改爲V. –

+0

這可以修復輸出參照空格的情況,但對於像!或其他人?我想從輸出中省略nonalphabet字符。這就是爲什麼我試圖在字符串上使用替換運算符 –

+0

如果它不是一個字母字符,else語句將導致它成爲'#' –