Python - Increment Characters in a String by 1

前端 未结 4 1190
野性不改
野性不改 2021-01-11 15:59

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-11 16:01

    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.

提交回复
热议问题