In this tutorial, we are going to see different methods to increment a character in Python.
Typecasting
Let's first see what happens if we add an int to char without typecasting.
Example
## str initialization char = "t" ## try to add 1 to char char += 1 ## gets an error
If you execute above program, it produces the following result −
TypeError Traceback (most recent call last) <ipython-input-20-312932410ef9> in <module>() 3 4 ## try to add 1 to char ----> 5 char += 1 ## gets an error TypeError: must be str, not int
To increment a character in a Python, we have to convert it into an integer and add 1 to it and then cast the resultant integer to char. We can achieve this using the builtin methods ord and chr.
Example
## str initialization char = "t" ## converting char into int i = ord(char[0]) ## we can add any number if we want ## incrementing i += 1 ## casting the resultant int to char ## we will get 'u' char = chr(i) print(f"Alphabet after t is {char}")
If you execute the above program, it produces the following result −
Alphabet after t is u
Bytes
There is another way to increment a character using bytes.
- Convert str into bytes.
- The result will an array containing ASCII values of all characters of a string.
- Adding 1 to the first char of converted bytes. The result will be an int.
- Convert the int into char.
Example
## str initialization char = "t" ## converting char to bytes b = bytes(char, 'utf-8') ## adding 1 to first char of 'b' ## b[0] is 't' here b = b[0] + 1 ## converting 'b' into char print(f"Alphabet after incrementing ACII value is {chr(b)}")
If you execute the above program, it produces the following result −
Alphabet after incrementing ACII value is u
If we have to string and converts it into bytes, then we can increment any character we want. Let's see it with an example.
Example
## str initialization name = "tutorialspoint" ## converting char to bytes b = bytes(name, 'utf-8') ## adding 1 to 'a' char of 'b' ## 'a' index is 6 b = b[6] + 1 ## converting 'b' into char print(f"name after incrementing 'a' char is tutori{chr(b)}lspoint")
If you execute the above program, it produces the following result −
name after incrementing ‘a’ char is tutoriblspoint
I hope you understand the concept well. If you have any doubt regarding the tutorial, please mention them in the comment section. Happy Coding :)