Change each character in string to the next charac

2020-06-29 07:50发布

I am coding in Python 2.7 using PyCharm on Ubuntu.

I am trying to create a function that will take a string and change each character to the character that would be next in the alphabet.

def LetterChanges(str):
    # code goes here
    import string
    ab_st = list(string.lowercase)
    str = list(str)
    new_word = []
    for letter in range(len(str)):
        if letter == "z":
            new_word.append("a")
        else:
            new_word.append(ab_st[str.index(letter) + 1])
        new_word = "".join(new_word)
    return new_word


# keep this function call here
print LetterChanges(raw_input())

When I run the code I get the following error:

/usr/bin/python2.7 /home/vito/PycharmProjects/untitled1/test.py
test
Traceback (most recent call last):
  File "/home/vito/PycharmProjects/untitled1/test.py", line 17, in <module>
    print LetterChanges(raw_input())
  File "/home/vito/PycharmProjects/untitled1/test.py", line 11, in LetterChanges
    new_word.append(ab_st[str.index(letter) + 1])
ValueError: 0 is not in list

Process finished with exit code 1

What am I doing wroing in line 11? How can I get the following character in the alphabet for each character and append it to the new list?

Many thanks.

7条回答
劳资没心,怎么记你
2楼-- · 2020-06-29 08:23

Here is a more general approach where user can choose how many characters back or forth they want to shift the string, and which alphabets they want to use:

from string import (ascii_lowercase,
                    ascii_uppercase)
from typing import Sequence


def shift(string: str,
          *,
          alphabets: Sequence[str] = (ascii_lowercase, ascii_uppercase),
          step: int = 1) -> str:
    """Shifts `string` by `step` in `alphabets`"""

    def shift_char(char):
        for alphabet in alphabets:
            try:
                return alphabet[(alphabet.index(char) + step) % len(alphabet)]
            except ValueError:
                pass
        return char

    return ''.join(map(shift_char, string))

Examples of usage:

# default parameters
>>> shift('abcxyz, ABCXYZ')
'bcdyza, BCDYZA'

# negative shift
>>> shift('abcxyz, ABCXYZ',
         step=-1)
'zabwxy, ZABWXY'

# using other alphabets
>>> russian_alphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
>>> shift('уегнп гбзмюсзм',
          alphabets=[russian_alphabet])
'фёдор двинятин'

Note on performance:

Note that alphabet[(alphabet.index(char) + step) % len(alphabet)] is O(n) due to searching of an index of an element in a string. While for small strings it's ok, for large strings it would make sense to have a dictionary mapping each character in an alphabet to its index, like:

mapping = dict(map(reversed, enumerate(alphabet)))
查看更多
登录 后发表回答