首页 > 解决方案 > 旋转字符串中的字符时保留大小写

问题描述

我需要编辑我的旋转功能以考虑大写字母,我对如何做到这一点感到困惑

下面是我的 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

标签: python

解决方案


推荐阅读