Change each character in string to the next character in alphabet

前端 未结 8 1127
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 15:45

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

8条回答
  •  一向
    一向 (楼主)
    2021-01-03 16:15

    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 of str. Instead, you can just use for 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.

    def LetterChanges(strng):
        ab_st = list(string.lowercase)
        output_string = []
        for letter in strng:
            if letter == 'z':
                output_string.append('a')
            else:
                letter_index = ab_st.index(letter) + 1
                output_string.append(ab_st[letter_index])
            new_word = "".join(output_string)
    
        return new_word
    
    
    # keep this function call here
    print LetterChanges(raw_input())
    

提交回复
热议问题