2016-07-25 103 views
1

請幫我寫一個函數,它接收一個字符char(即一個長度爲1的字符串)和一個整數旋轉。我的函數應該返回一個長度爲1的新字符串,這是由旋轉的位置向右旋轉的結果。我對這段代碼的輸出應該是這樣的:Python字符旋轉

print(alphabet_position(a, 13)) = Output = n 
print(alphabet_position(A, 14)) = Output = (capital) O 
print(alphabet_position(6, 13)) = Output = 6 

我的功能看起來像這樣

def alphabet_position(letter, number): 
    for char in letter: 
     return ord(char)+ number 
print(alphabet_position("g", 2)) 
print(alphabet_position("Z", 2)) 

輸出爲105 輸出爲92

+0

'print(alphabet_position(「Z」,2))'return?是「B」嗎? –

回答

2

你忘了做檢查你已經提到並且還需要使用chr(returnedValue)將返回的整數轉換爲字符。請查看以下功能代碼

def alphabet_position(letter, number): 
    if len(letter) != 1: 
     return -1 #Invalid input 
    elif letter.isalpha() == False: 
     return letter #If its not an alphabet 
    else: 
     ans = ord(letter) + number 
     # the below if-statement makes sure the value does not overflow. 
     if ans > ord('z') and letter.islower(): 
      ans = ans - ord('z') + ord('a') 
     elif ans > ord('Z') and letter.isupper(): 
      ans = ans - ord('Z') + ord('A') 
     return chr(ans) 
+0

非常歡迎。如果你喜歡我的回答,請注意。 –

+0

謝謝。我沒有檢查功能。輸出是:print(alphabet_position(「a」,0))=輸出應該是一個 print(alphabet_position(「A」,13))=輸出應該是N print(alphabet_position(「a」,13))=輸出應該是n但是輸出是H,N,U – white

+0

很抱歉,您的評論是不可理解的。 –