Liam Emery Liam Emery - 3 months ago 9
Python Question

how can I move a list index value forward 'x' amount of times using python?

I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.

For example if the code was

abc


Then the solution would be

cde


So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like the following)

alphabet = ["a","b","c"...."z"]


I am trying to write code similar to this

def scramble(sentence):
alphabet = ["a","b","c"...]
solution = []
for i in sentence:
newIndex = get index value of i, += 2
newLetter = translate newIndex into the corresponding letter
solution.append(newLetter)
for i in solution:
print(i, end="")


But I am not yet skilled enough in python to figure it out

Answer

Try:

>>> s = 'abc'
>>> ''.join(chr(ord(c)+2) for c in s)
'cde'

The above is not limited to standard ASCII: it works up through the unicode character set.

Limiting ourselves to 26 characters

>>> s = 'abcyz'
>>> ''.join(chr(ord('a')+(ord(c)-ord('a')+2) % 26) for c in s)
'cdeab'

Modifying the original code

If we want to modify the original only enough to get it working:

from string import ascii_lowercase as alphabet

def scramble(sentence):
    solution = []
    for i in sentence:
        newIndex = (alphabet.index(i) + 2) % 26
        newLetter = alphabet[newIndex]
        solution.append(newLetter)
    for i in solution:
        print(i, end="")

Example:

>>> scramble('abcz')
cdeb