Trim
Trim

Reputation: 373

python "incrementing" a character string?

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?

Upvotes: 4

Views: 10433

Answers (3)

Siyaram Malav
Siyaram Malav

Reputation: 4698

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.

Upvotes: 1

Carson Myers
Carson Myers

Reputation: 38564

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

Upvotes: 5

Vincent Savard
Vincent Savard

Reputation: 35927

You could use ord and chr :

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

More information about ord and chr.

Upvotes: 14

Related Questions