Text Shift function in Python

后端 未结 5 430
陌清茗
陌清茗 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:30

    You are looping over the list of characters, and i is thus a character. You then try to store that back into data using the i character as an index. That won't work.

    Use enumerate() to get indexes and the values:

    def shifttext(shift):
        input=raw_input('Input text here: ')
        data = list(input)
        for i, char in enumerate(data):
            data[i] = chr((ord(char) + shift) % 26)
        output = ''.join(data)
        return output
    

    You can simplify this with a generator expression:

    def shifttext(shift):
        input=raw_input('Input text here: ')
        return ''.join(chr((ord(char) + shift) % 26) for char in input)
    

    But now you'll note that your % 26 won't work; the ASCII codepoints start after 26:

    >>> ord('a')
    97
    

    You'll need to use the ord('a') value to be able to use a modulus instead; subtracting puts your values in the range 0-25, and you add it again afterwards:

        a = ord('a')
        return ''.join(chr((ord(char) - a + shift) % 26) + a) for char in input)
    

    but that will only work for lower-case letters; which might be fine, but you can force that by lowercasing the input:

        a = ord('a')
        return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in input.lower())
    

    If we then move asking for the input out of the function to focus it on doing one job well, this becomes:

    def shifttext(text, shift):
        a = ord('a')
        return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in text.lower())
    
    print shifttext(raw_input('Input text here: '), 3)
    

    and using this on the interactive prompt I see:

    >>> print shifttext(raw_input('Input text here: '), 3)
    Input text here: Cesarsalad!
    fhvduvdodgr
    

    Of course, now punctuation is taken along. Last revision, now only shifting letters:

    def shifttext(text, shift):
        a = ord('a')
        return ''.join(
            chr((ord(char) - a + shift) % 26 + a) if 'a' <= char <= 'z' else char
            for char in text.lower())
    

    and we get:

    >>> print shifttext(raw_input('Input text here: '), 3)
    Input text here: Ceasarsalad!
    fhdvduvdodg!
    

提交回复
热议问题