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')+...
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?
5 Answers
str(unichr(c)) can be replaced with just chr(c).
Simplified version:
chr(ord('b') + 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'
You can do something like:
class char(unicode):
def __add__(self, x):
return char(unichr(ord(self) + x))
print char('a') + 1 # b