Python - Increment characters in a string by 1

I was looking for how to do this in python and I cannot find the answer. If you have a line:

>>> value = 'abc' 

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

 >>> value = 'bcd' 

I know that I can do this with a single 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 an 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 any way to do this?

+5
source share
4 answers

You can use the 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 repeats each letter in the value string and increments it by one using the chr(ord(letter)+1) methodology suggested in your question. Then it uses ''.join() to convert the letters in the generator back to string.

+8
source

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

 value = 'abc' ''.join(map(lambda x:chr(ord(x)+1),value)) 
+7
source

A very simple four-line code snippet:

 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 it to it, but this does not work with "z", so you can 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
source
 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 really worked thanks to a call using python 3

0
source

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


All Articles