How Can I Do 'A' + 1 #=> 'B' in Python?

How Can I Do 'A' + 1 #=> 'B' in Python?

I'm working on a project need this functionality very frequently

'b' + 1 #=> 'a' and 'b' - 1 #=> 'a'

Now my solution is very tedious :

str(unichr((ord('b')+ 1))) 

is there a more elegant way to do this?

1

5 Answers

str(unichr(c)) can be replaced with just chr(c).

Simplified version:

chr(ord('b') + 1)
1

define your own function:

In [103]: def func(c,n):
    return chr(ord(c)+n)
   .....: 

In [105]: func('a',-1)
Out[105]: '`'

In [106]: func('b',-1)
Out[106]: 'a'

In [107]: func('c',2)
Out[107]: 'e'

Python is strongly typed and considerer strings and ints are different, and won't convert one to another implicitly.

However, you code can probably be simplified to

chr(ord('b') + 1)

If you use it a lot, put it in a function, and don't worry about it any more :

def incr_char(c, n):
    return chr(ord(c) + n)

Try this instead:

>>> import string
>>> string.letters[string.letters.index('a')+1]
'b'

Just for Ashwini:

>>> string.letters[string.letters.index('a')-1]
'Z'
1

You can do something like:

class char(unicode):
    def __add__(self, x):
        return char(unichr(ord(self) + x))

print char('a') + 1 # b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.