How can I increment a char?
Asked Answered
A

7

119

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?

Algoid answered 28/1, 2010 at 18:28 Comment(4)
Traditional for loop: for i in range(50): do_something_with(i). Come on, that's not so bad!!Rossner
@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.Algoid
you seem to be looking for something like [''.join(i) for i in itertools.product(string.ascii_lowercase, repeat=2)]Neckcloth
@SilentGhost: Is that all it takes? If only it said in the manual.Algoid
D
201

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'
Darnelldarner answered 28/1, 2010 at 18:28 Comment(2)
@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).Hobbes
worked like a charm. <br> The only change I'd do is for z, in which case I've assigned an 'a'.Englishman
C
16

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

Coercive answered 28/1, 2010 at 18:38 Comment(0)
S
6

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

Spadix answered 8/4, 2020 at 14:30 Comment(0)
D
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
Demarcusdemaria answered 7/5, 2017 at 15:1 Comment(0)
C
4

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'
Conditioner answered 16/12, 2019 at 12:22 Comment(0)
S
0
def doubleChar(str):
    result = ''
    for char in str:
        result += char * 2
    return result

print(doubleChar("amar"))

output:

aammaarr
Schaaff answered 17/1, 2019 at 3:59 Comment(0)
M
-1

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)
Measures answered 14/10, 2020 at 14:47 Comment(2)
You have used same logic as accepted answer, what is the point of having new answer with similar solution?Biff
i like clean code, in this section have not seen any solution that satisfies me, thus i put my 2 cents.Measures

© 2022 - 2024 — McMap. All rights reserved.