Python code to modify string does not work properly

This piece of code should accept string input and output another string, which is only a modified version of the input string. I can not make it work.

It is supposed to print a line in which each letter is the next letter of the input string. But after running the code, it simply displays the same input string instead of the modified string.

def str_changer(string):

       string_list = list(string)
       alphabets = 'abcdefghijklmnopqrstuvwxyz'
       positions = []
       for letter in string_list:
         positions.append(alphabets.index(letter))
       for each in positions:
         each = each + 1
       for each in string_list:
         string_list[string_list.index(each)] = 
       alphabets[positions[string_list.index(each)]]

       another = ''.join(string_list)



       return another



    lmao = raw_input('Enter somin\'')
    print str_changer(lmao)
+4
source share
2 answers

This should work for you. You must use %for accounting z.

The main thing is that you do not need to explicitly create a list of positions.

def str_changer(string):

    string_list = list(string)
    alphabets = 'abcdefghijklmnopqrstuvwxyz'

    new_string_list = []

    for letter in string_list:
        new_string_list.append(alphabets[(alphabets.index(letter)+1) % len(alphabets)])

    return ''.join(new_string_list)

lmao = raw_input('Enter somin\'')
print str_changer(lmao)
+3
source

You can only do this in 1 line :

s = 'abcdz'
print(''.join(chr(ord(letter) + 1) if letter != 'z' else 'a' for letter in s))
# bcdea

Demo

>>> ord('a')
97
>>> ord('b')
98
>>> chr(ord('a') + 1)
'b'
+7
source

Source: https://habr.com/ru/post/1695775/


All Articles