incrementing characters

Nick Perkins nperkins7 at home.com
Mon Jul 23 14:22:02 EDT 2001


"Holland King" <insanc at cc.gatech.edu> wrote in message
news:9jhojp$t7h$1 at solaria.cc.gatech.edu...
> how do you interate a letter or string? for instance:
> a + 1 = b
> or
> aa + 1 = ab
> etc. in c it is similar to above and i am guessing there is an equally
> simple way to do it in python, i just can't figure it out. thank you
> for your time and help.
>
> --
> ---
> Joseph Holland King  | "God whispers to us in our pleasures, speaks in our
>                      |  conscience, but shouts in our pains: it is His
>                      |  megaphone to rouse a deaf world." C. S. Lewis


I think you mean "increment"...
For one character, it's simple:

>>> ord('A')
65
>>> chr(65)
'A'
>>> chr(66)
'B'

For a string, you will have to mess around a bit.
Remember, strings are immutable, so you will have to construct a new string.

def inc_char(ch): return chr(ord(ch)+1)
def inc_string(s): return s[:-1] + inc_char(s[-1])

..add you own error checking, etc...






More information about the Python-list mailing list