开发者

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开发者_如何学Go, but is there any way to do this in python?


You could use ord and chr :

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

More information about ord and chr.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜