Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do 'a' + 1 #=> 'b' in python?

Tags:

python

string

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?

like image 591
mko Avatar asked Dec 21 '22 15:12

mko


2 Answers

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

Simplified version:

chr(ord('b') + 1)
like image 163
Mark Byers Avatar answered Jan 13 '23 18:01

Mark Byers


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'
like image 32
Ashwini Chaudhary Avatar answered Jan 13 '23 19:01

Ashwini Chaudhary