Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment a char?

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?

like image 570
Tom R Avatar asked Jan 28 '10 18:01

Tom R


People also ask

Can we increment char in C?

Yes, you can apply the ++ increment operator to an object of type char , with the expected results in most cases: char c = 42; c++; printf("c = %d\n", c); // prints 43.

Can char be incremented in Java?

You can't. Strings are immutable. You can just reference a new string object that has 0 characters.

What happens when you increment a char in C?

Because your compiler defaults char to signed char . So the range of values for it is -128 to 127, and incrementing 127 is triggering wraparound. If you want to avoid this, be explicit, and declare your variable as unsigned char .

What does char ++ do in Java?

The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.


1 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' 
like image 80
Eli Bendersky Avatar answered Oct 12 '22 02:10

Eli Bendersky