Python - Increment Characters in a String by 1

前端 未结 4 1191
野性不改
野性不改 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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 16:06

    As gtllambert beat me to my original answer, I am posting an alternative solution. You can also use map and a lambda expression to achieve the same. The lambda expression uses chr and ord to increment each character by one and chr is used to convert it back to a character.

    value = 'abc'
    ''.join(map(lambda x:chr(ord(x)+1),value))
    
    0 讨论(0)
  • 2021-01-11 16:18
    value = 'abc'
    newVar=(chr(ord(value[0])+1))
    newVar1=(chr(ord(value[1])+1))
    newVar2=(chr(ord(value[2])+1))
    value=newVar+newVar1+newVar2
    print(value)
    

    Here is what I came up with can't believe it actually worked thanks for the challenge using python 3

    0 讨论(0)
提交回复
热议问题