4

I know in java, if you have a char variable, you could do the following:

char a = 'a'
a = a + 1
System.out.println(a)

This would print 'b'. I don't know the exact name of what this is, but is there any way to do this in python?

Trim
  • 375
  • 1
  • 5
  • 14
  • 2
    In Java, a `char` value is essentially the same as an unsigned 16-bit integer. So, incrementing it is really just incrementing it. However, Python does not treat characters interchangeably with integers. – Greg Hewgill Nov 14 '10 at 19:29
  • 1
    To elaborate on what Greg said, how would you increment "I am a string"? Because that's what a 'char' is in Python: a string that happens to have length 1. – aaronasterling Nov 14 '10 at 19:35
  • Possible duplicate of [Python: How can I increment a char?](http://stackoverflow.com/questions/2156892/python-how-can-i-increment-a-char) – outis Feb 14 '16 at 00:58

3 Answers3

14

You could use ord and chr :

print(chr(ord('a')+1))
# b

More information about ord and chr.

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
5

As an alternative,

if you actually need to move over the alphabet like in your example, you can use string.lowercase and iterate over that:

from string import lowercase

for a in lowercase:
    print a

see http://docs.python.org/library/string.html#string-constants for more

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
Carson Myers
  • 37,678
  • 39
  • 126
  • 176
1

Above solutions wont work when char is z and you increment that by 1 or 2,

Example: if you increment z by incr (lets say incr = 2 or 3) then (chr(ord('z')+incr)) does not give you incremented value because ascii value goes out of range.

for generic way you have to do this

i = a to z any character
incr = no. of increment
#if letter is lowercase
asci = ord(i)
if (asci >= 97) & (asci <= 122):            
  asci += incr
  # for increment case
  if asci > 122 :
    asci = asci%122 + 96
    # for decrement case
    if asci < 97:
      asci += 26
    print chr(asci)

it will work for increment or decrement both.

same can be done for uppercase letter, only asci value will be changed.

Siyaram Malav
  • 4,414
  • 2
  • 31
  • 31