python - 旋转字符串中的字符时保留大小写
问题描述
我需要编辑我的旋转功能以考虑大写字母,我对如何做到这一点感到困惑
下面是我的 Python 代码:
from helper import alphabet_position, rotate
def encrypt(text,key):
#Declare variable
cipher = ''
#Compute length
l = len(key)
#Assign value
idx = 0
#Loop
for i in text:
#if condition satisfies
if i.isalpha():
#Call method
cipher += rotate(i,alphabet_position(key[idx]))
#Update to next
idx = (idx+1)%len(key)
#Otherwise
else:
#Increment
cipher += i
#Return
return cipher
#Define main
def main():
#Get text from user
text = input("Type a message:" )
#Get key from user
key = input("Encrption key:" )
#Call method
cipher = encrypt(text,key)
#Display result
print(cipher)
#Call main
if __name__ == "__main__":
main()
但返回以下错误
✖ ︎For vigenere.encrypt('Sailing <3 ship thru br0ken Harbors',
You should have returned this:
'Feqwgba <3 fnvta effo ox0xiv syfvbxf'
But you actually returned this:
'feqwgba <3 fnvta effo ox0xiv syfvbxf'
✖ ︎对于 vigenere.encrypt('BaRFoo', 'BaZ')
You should have returned this:
'CaQGon'
But you actually returned this:
'caqgon'
我如何让它第一个字母大写?
字母位置和旋转字符如下:
import string
alphabet_pos = "abcdefghijklmnopqrstuvwxyz"
def alphabet_position(letter):
pos = alphabet_pos.index(letter.lower())
return pos
def rotate(letter, rot):
pos = alphabet_position(letter)
new_pos = (pos + rot) % 26
new_char = alphabet_pos[new_pos]
return new_char
解决方案
推荐阅读
- javascript - 模块显示模式的参考错误
- python - 将 json 补丁应用到 Mongoengine 文档
- hsm - 使用 PKCS11 设置 Docker
- python - 如何使用 Group By 和 Join 访问对象 User (django admin)?
- asp.net - ASP.Net 随机会话超时
- c# - Azure WebJobs SDK 和模拟器 - 触发器不起作用
- c# - 从非常大的 int 数组 c# 初始化特定索引
- assembly - 寄存器间接模式的 x86 机器码格式
- reactjs - localhost http 500 内部服务器错误条带反应
- python-3.6 - cursor.fetchall() 抛出索引或范围错误