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

Byte String: 

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.

Implementation:

string="codespeedy"
print("String is ",string)
#convert to bytes
byte=bytes(string,'utf-8')
byte=byte[3]+1
#convert back to character
c=chr(byte)
print("Increment "+string[3]+"-to-",c)

Output:

String is codespeedy
Increment e-to-f

 

Type Casting:

 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.

Implementation:

string="codespeedy"
print("The String is ",string)
#converting it to integer
s=ord(string[0])
s=s+1
#converting back to character
c=chr(s)
print("Increment "+string[0]+"-to-",c)

Output:

The String is codespeedy
Increment c-to-d

Leave a Reply