How can I increment a char?

Question:

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?

Asked By: Tom R

||

Answers:

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'
Answered By: Eli Bendersky

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

Answered By: S.Lott

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
Answered By: xpuu
def doubleChar(str):
    result = ''
    for char in str:
        result += char * 2
    return result

print(doubleChar("amar"))

output:

aammaarr
Answered By: Amar Tanwar

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'
Answered By: Moein Kameli

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

Answered By: Jaydeep_GAME

For me i made the fallowing as a test.

string_1="abcd"

def test(string_1):
   i = 0
   p = ""
   x = len(string_1)
   while i < x:
    y = (string_1)[i]
    i=i+1
    s = chr(ord(y) + 1)
    p=p+s

   print(p)

test(string_1)
Answered By: Milan Popovic

We can increment character in many ways –

Method 1: Using ascii_uppercase –

import string
ch = input("Enter a character")
alphabets = string.ascii_uppercase
chIndex = alphabets.index(ch)
nextCh = alphabets[(chIndex + 1) % 26]
print(nextCh)

Method 2: Using ord() and Some Math Calculations –

ch = input("Enter a character")
nextCh = (((ord(ch) + 1) - 64) % 26) + 64
print(chr(nextCh))

There are many other ways in which we can increment a character in Lowercase or Uppercase both –

  1. Using ord() and chr() Functions
  2. Using bytes() and str() Functions
  3. Using bytes() and chr() Functions
  4. Using ord() and Some Math Calculations
  5. Using ascii_lowercase and ascii_uppercase
Answered By: Rajeev Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.