Ways to increment a character in Python
In python there is no implicit concept of data types, though explicit conversion of data types is possible, but it not easy for us to instruct operator to work in a way and understand the data type of operand and manipulate according to that. For e.g Adding 1 to a character, if we require to increment the character, an error instructing type conflicts occur, hence other ways need to be formulated to increment the characters.
# python code to demonstrate error # due to incrementing a character # initializing a character s = 'M' # trying to get 'N' # produces error s = s + 1 print (s) |
Output:
Traceback (most recent call last):
File "/home/fabc221bf999b96195c763bf3c03ddca.py", line 9, in
s = s + 1
TypeError: cannot concatenate 'str' and 'int' objects
# python code to demonstrate way to # increment character # initializing character ch = 'M' # Using chr()+ord() # prints P x = chr(ord(ch) + 3) print ("The incremented character value is : ",end="") print (x) |
Output:
The incremented character value is : P
Explanation : ord() returns the corresponding ASCII value of character and after adding integer to it, chr() again converts it into character.
# python code to demonstrate way to # increment character # initializing byte character ch = 'M' # converting charater to byte ch = bytes(ch, 'utf-8') # adding 10 to M s = bytes([ch[0] + 10]) # converting byte to string s = str(s) # printing the required value print ("The value of M after incrementing 10 places is : ",end="") print (s[2]) |
Output:
The value of M after incrementing 10 places is : W
Explanation : The character is converted to byte string , incremented, and then again converted to string form with prefix “‘b”, hence 3rd value gives the correct output.
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Python PIL | BoxBlur() method
- Python | sympy.ones() method
- Python | sympy.zeros() method
- Python | sympy.eye() method
- How to write an empty function in Python - pass statement?
- Operator Functions in Python | Set 2
- Find the first non-repeating character from a stream of characters
- Time Functions in Python | Set-2 (Date Manipulations)
- Send mail from your Gmail account using Python
- Python – The new generation Language
- Print Single and Multiple variable in Python
- Increment and Decrement Operators in Python
- str() vs repr() in Python
- Swap two variables in one line in C/C++, Python, PHP and Java
- Generate all permutation of a set in Python



