Python字符旋转 [英] Python character rotation
本文介绍了Python字符旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你能帮我写一个函数,它接收一个字符char(即长度为1的字符串)和一个整数旋转.我的函数应该返回一个长度为 1 的新字符串,这是通过向右旋转位置数旋转字符的结果.我这段代码的输出应该是这样的:
Could you please help me with writing a function, which receives a character char (ie., a string of length one ), and an integer rotation. My function should return a new string of length one, the resulting of rotating char by rotation number of places to the right. My output for this code should be like this:
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
The output is 105 The output is 92
推荐答案
你忘了做你提到的检查,而且,你需要使用 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)
这篇关于Python字符旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文