Python - Increment Characters in a String by 1

前端 未结 4 1219
野性不改
野性不改 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:00

    Very simple four line piece of code:

    finalMessage=""
    for x in range (0,len(value)):
        finalMessage+=(chr(ord(value[x])+1))
    print(finalMessage)
    

    It goes through each letter in the string and adds one to it, but this doesn't work with "z", so you could do:

    value="abc testing testing, or sdrshmf"
    finalMessage=""
    for x in range(0,len(value)):
        if ord(value[x]) in range(97,123):
            finalMessage+=(chr(((ord(value[x])-96)%26)+97))
        elif ord(value[x]) in range(65,91):
            finalMessage+=(chr(((ord(value[x])-64)%26)+65))
        else:
            finalMessage+=value[x]
    print(finalMessage)
    

提交回复
热议问题