How can I increment a char?

143,165

Solution 1

In Python 2.x, just use the ord and chr functions:

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 

Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord receives Unicode chars and chr produces them).

But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:

>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'

Solution 2

"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.

Solution 3

Check this: USING FOR LOOP

for a in range(5):
    x='A'
    val=chr(ord(x) + a)
    print(val)

LOOP OUTPUT: A B C D E

Solution 4

I came from PHP, where you can increment char (A to B, Z to AA, AA to AB etc.) using ++ operator. I made a simple function which does the same in Python. You can also change list of chars to whatever (lowercase, uppercase, etc.) is your need.

# Increment char (a -> b, az -> ba)
def inc_char(text, chlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    # Unique and sort
    chlist = ''.join(sorted(set(str(chlist))))
    chlen = len(chlist)
    if not chlen:
        return ''
    text = str(text)
    # Replace all chars but chlist
    text = re.sub('[^' + chlist + ']', '', text)
    if not len(text):
        return chlist[0]
    # Increment
    inc = ''
    over = False
    for i in range(1, len(text)+1):
        lchar = text[-i]
        pos = chlist.find(lchar) + 1
        if pos < chlen:
            inc = chlist[pos] + inc
            over = False
            break
        else:
            inc = chlist[0] + inc
            over = True
    if over:
        inc += chlist[0]
    result = text[0:-len(inc)] + inc
    return result

Solution 5

There is a way to increase character using ascii_letters from string package which ascii_letters is a string that contains all English alphabet, uppercase and lowercase:

>>> from string import ascii_letters
>>> ascii_letters[ascii_letters.index('a') + 1]
'b'
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Also it can be done manually;

>>> letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> letters[letters.index('c') + 1]
'd'
Share:
143,165

Related videos on Youtube

Tom R
Author by

Tom R

Good times with C, Java, Python on web and embedded devices.

Updated on July 08, 2022

Comments

  • Tom R
    Tom R almost 2 years

    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?

    • jathanism
      jathanism over 14 years
      Traditional for loop: for i in range(50): do_something_with(i). Come on, that's not so bad!!
    • Tom R
      Tom R over 14 years
      @SilentGhost: I'm splitting up an English dictionary for use in an Android app. Because the file individually is too big, I've written a Python script to split them up into words_aa.txt, words_ab.txt, etc... I needed to write a second script to generate a Java file with an array containing the Ids of the raw file resources of each word file (because I'm lazy), and I couldn't think of a better way to do it.
    • SilentGhost
      SilentGhost over 14 years
      you seem to be looking for something like [''.join(i) for i in itertools.product(string.ascii_lowercase, repeat=2)]
    • Tom R
      Tom R over 14 years
      @SilentGhost: Is that all it takes? If only it said in the manual.
  • mjv
    mjv over 14 years
    @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).
  • user45949
    user45949 over 9 years
    worked like a charm. <br> The only change I'd do is for z, in which case I've assigned an 'a'.
  • Ruli
    Ruli over 3 years
    You have used same logic as accepted answer, what is the point of having new answer with similar solution?
  • Milan Popovic
    Milan Popovic over 3 years
    i like clean code, in this section have not seen any solution that satisfies me, thus i put my 2 cents.