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)
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'
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With