Ways to increment a character in Python
Here you will learn the ways to increment a character in the Python Programming Language. We will do it basically by using two methods,
- Byte Strings
- Type Casting
Let us understand each of the methods in a detailed manner and also implementing the same,
Python program to increment a character
In byte string type conversion we generally convert the character to bytes, as a result, an array is formed to contain the ASCII values of the characters in the inputted string.
If we increment the bytes array at a particular character then the result will be stored as type ‘int’, so that we have to again typecast it to string to display the incremented character.
string="codespeedy" print("String is ",string) #convert to bytes byte=bytes(string,'utf-8') byte=byte+1 #convert back to character c=chr(byte) print("Increment "+string+"-to-",c)
String is codespeedy Increment e-to-f
As we are using Python, we only have access to the explicit conversion of data and hence we cannot directly increment a character in a string.
To do so, we have to convert the character to an integer using ord() and increment it. After the incrementation is done we have to again convert it to a character using chr() to display the incremented character in the inputted string.
string="codespeedy" print("The String is ",string) #converting it to integer s=ord(string) s=s+1 #converting back to character c=chr(s) print("Increment "+string+"-to-",c)
The String is codespeedy Increment c-to-d
Leave a Reply