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.
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:
Examples of usage:
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: