Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code for string modification doesn't work properly

This piece of code's supposed to take in a string input and output another string which is just the modified version of the input string. I can't get it to work though.

It is supposed to output a string in which each letter is the next alphabetic letter of the input string.But upon running the code, its simply outputs 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)
like image 357
StealthyPanda Avatar asked Dec 24 '22 08:12

StealthyPanda


2 Answers

You could do it in just 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'
like image 54
Austin Avatar answered Jan 09 '23 07:01

Austin


This should work for you. You should use % to account for z.

The main point is you don't need to explicitly build 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)
like image 42
jpp Avatar answered Jan 09 '23 07:01

jpp