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.
Two main things. 1) Don't use the Python built-in
str
to define variables as it could lead to unusual behaviour. 2)for letter in range(len(str))
does not return a letter at all (hence the error stating that 0 is not in your list). Instead, it returns numbers one by one up to the length ofstr
. Instead, you can just usefor letter in my_string
.EDIT: Note that you don't need to convert the string into a list of letters. Python will automatically break the string into individual letters in
for letter in strng
. Updated answer based on comment from linus.There's two issues with the code. Instead of looping letters you're looping over numbers since you're calling
range(len(str))
. The second issue is that within the loop you assign a string tonew_word
which will cause the next iteration to fail sincestring
doesn't have methodappend
. If you make the following changes it should work:Look at this for ideas to simplify your code.
I think you are making this too complicated.
Just use modulo to roll around to the beginning of the string:
Which you can reduce to a single unreadable line if you wish:
Either case,
If you want it to be limited to upper of lower case letters, just change the import:
The problem you are solving is of Ceaser cipher. you can implement the formula in your code.
E(x) = (x+n)%26 where x is your text and n will be the shift.
Below is my code. (I write the code in python 3)
this is my code i think it is very simple