Text Shift function in Python

后端 未结 5 421
陌清茗
陌清茗 2020-12-03 15:50

I\'m writing code so you can shift text two places along the alphabet: \'ab cd\' should become \'cd ef\'. I\'m using Python 2 and this is what I got so far:

         


        
5条回答
  •  时光取名叫无心
    2020-12-03 16:22

    Martijn's answer is great. Here is another way to achieve the same thing:

    import string
    
    def shifttext(text, shift):
        shift %= 26 # optional, allows for |shift| > 26 
        alphabet = string.lowercase # 'abcdefghijklmnopqrstuvwxyz' (note: for Python 3, use string.ascii_lowercase instead)
        shifted_alphabet = alphabet[shift:] + alphabet[:shift]
        return string.translate(text, string.maketrans(alphabet, shifted_alphabet))
    
    print shifttext(raw_input('Input text here: '), 3)
    

提交回复
热议问题