views:

975

answers:

2

I'm new to Python, coming from Java and C. How can I increment a char? In Java or C, chars and ints are practically interchangeable, and in certain loops, it's very useful to me to be able to do increment chars, and index arrays by chars.

How can I do this in Python? It's bad enough not having a traditional for(;;) looper - is there any way I can achieve what I want to achieve without having to rethink my entire strategy?

Any help appreciated.

+14  A: 

Use the ord and chr functions

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 
Eli Bendersky
Very quick! Thanks. Does make me miss 'the good old days', though.
Tom R
The good old days where everything was way too hard? Pshaw!
jathanism
@Tom R. Don't! [miss the old days]. As you are trying a quickly achieve something or convert a piece of code, concepts and idioms of Python may seem to merely impede your progress and hardly be worth the learning curve... Be patient! You may even find that gaining proficiency in Python will improve your style in Java (and C, to a lesser extent).
mjv
+5  A: 

"bad enough not having a traditional for(;;) looper"?? What?

Are you trying to do

import string
for c in string.lowercase:
    ...do something with c...

Or perhaps you're using string.uppercase or string.letters?

Python doesn't have for(;;) because there are often better ways to do it. It also doesn't have character math because it's not necessary, either.

S.Lott
+1 for trying to answer the question behind the question (XY problem, and so on). If I could, I'd give you more.
Devin Jeanpierre
Thanks. I'm often first to ask "why?" for questions like this. But @SilentGhost beat me to it.
S.Lott