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
This can be done much easier and efficiently by using a look-up instead of using index
for each letter.
look_up = dict(zip(string.ascii_lowercase, string.ascii_lowercase[1:]+'a'))
The zip above creates tuples of the form ('a', 'b')...
including ('z', 'a')
. Feeding that into the dict constructor makes a dict of the same form.
So now the code can be simply:
def LetterChanges(s):
from string import ascii_lowercase
look_up = dict(zip(ascii_lowercase, ascii_lowercase[1:]+'a'))
new_s = ''
for letter in s:
new_s += look_up[letter]
return new_s
Even this dict creation and the loop can be saved by using the str.maketrans method and feeding its result to str.translate:
def LetterChanges(s):
from string import ascii_lowercase
return s.translate(str.maketrans(ascii_lowercase, ascii_lowercase[1:]+'a'))