Search code examples
pythonsubtraction

Subtract letters in Python


I'm trying to subtract letters in Python, but I can't do it the proper way.

I know how to get the ord of the letter.

Like:

a = "a"
x = ord(a)   # -> this will give me 97.

When I try to subtract values from that letter I get a completely different result than what I wanted.

If I subtract 1 from b I get 97 (which represents a), but now I want to subtract 14 from b, and I want to reach a, then go back to z and continues the subtraction.

a = 97
b = 98
...
z = 122

I want to continue looping in the lower case alphabet, which is between 97 and 122.

Example, If I subtract 14 from b, I get 84, but in the way that I want to do it I wanted to get n.

b - 14 = a - 13 = z - 12 (...) and so on.

I hope you could understand what I meant to say.

;)

Can anyone help me here ?

Regards, Ivan.


Solution

  • I would isolate just the lower case letters, then use slicing to your advantage. When you subtract past the beginning of the list, you will get a negative index, which will start indexing from the back of the list. This should give you the behavior you expect.

    >>> s = 'abcdefghijklmnopqrstuvwxyz'
    >>> s.find('c')
    2
    >>> s[s.find('c') - 6]
    'w'
    

    Note that to make sure that + still works, you need to use the % operator in case you wrap around the list going forward.

    >>> s.find('x')
    23
    >>> s[(s.find('x') + 5) % 26]
    'c'
    >>> s[(s.find('c') - 6) % 26]
    'w'