Does Python "increment" a character string?

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

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

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

+3
source share
3 answers

You can use ord and chr:

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

Additional information about ord and chr .

+13
source

As an alternative

if you really need to navigate alphabetically, as in your example, you can use string.lowercaseand iterate over it:

from string import lowercase

for a in lowercase:
    print a

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

+5

, char z, 1 2,

Example: if you increment z by incr (say incr = 2 or 3), then (chr (ord ('z') + incr)) does not give you an increasing value because the ascii value is out of range.

for the general way that you should 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 to increase or decrease both.

the same can be done for a capital letter, only the asci value will be changed.

0
source

Source: https://habr.com/ru/post/1774816/


All Articles