Python - Increment Characters in a String by 1

brazjul picture brazjul · Mar 5, 2016 · Viewed 22.8k times · Source

I've searched on how to do this in python and I can't find an answer. If you have a string:

>>> value = 'abc' 

How would you increment all characters in a string by 1? So the input that I'm looking for is:

>>> value = 'bcd' 

I know I can do it with one character using ord and chr:

>>> value = 'a'
>>> print (chr(ord(value)+1)) 
>>> b

But ord() and chr() can only take one character. If I used the same statement above with a string of more than one character. I would get the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 3 found 

Is there a way to do this?

Answer

gtlambert picture gtlambert · Mar 5, 2016

You could use a generator expression with ''.join() as follows:

In [153]: value = 'abc'

In [154]: value_altered = ''.join(chr(ord(letter)+1) for letter in value)

In [155]: value_altered
Out[155]: 'bcd'

The generator iterates over each letter in the string value and increments it by one using the chr(ord(letter)+1) methodology suggested in your question. It then uses ''.join() to convert the letters in the generator back into a string.