Open In App

Ways to increment a character in Python

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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

 

Using ord() + chr()

 

Python3




# 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.
 

Using byte string

 

Python3




# python code to demonstrate way to
# increment character
 
# initializing byte character
ch = 'M'
 
# converting character 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.

Use the string module:

One additional approach to incrementing a character in Python is to use the string module’s ascii_uppercase or ascii_lowercase constant, depending on the case of the character you want to increment. These constants contain the uppercase or lowercase ASCII letters, respectively, as a string. You can then use the index method of the string to find the index of the character you want to increment, add 1 to that index, and use the resulting index to retrieve the next character from the appropriate constant.

Here is an example of how you could use this approach:

Python3




import string
 
# Initialize character
ch = 'M'
 
# Increment character
if ch.isupper():
    # Use ascii_uppercase if character is uppercase
    letters = string.ascii_uppercase
else:
    # Use ascii_lowercase if character is lowercase
    letters = string.ascii_lowercase
 
# Find index of character in letters
index = letters.index(ch)
 
# Increment index and retrieve next character from letters
next_char = letters[index + 1]
 
print(f"The next character after {ch} is {next_char}")


Output

The next character after M is N

Auxiliary space: O(1), or constant space. The code uses a fixed number of variables, regardless of the size of the input. Specifically, the code uses:

  1. The variable ch stores a single character.
  2. The variable letters to store a list of either uppercase or lowercase letters, depending on the case of ch.
  3. The variable index to store the index of ch in letters.
  4. The variable next_char to store the character after ch in letters.
     

Since the number of variables used is fixed and does not depend on the size of the input, the space complexity of the code is O(1).

Time complexity: O(1), or constant time. The code performs a fixed number of operations regardless of the size of the input. Specifically, the code:

  1. Initializes the variable ch with a single character.
  2. Determines whether ch is an uppercase or lowercase character.
  3. Finds the index of ch in the list of uppercase or lowercase letters.
  4. Increments the index and retrieves the character at the new index.
  5. Prints a message with the original character and the next character.

Since the number of operations is fixed and does not depend onthe size of the input, the time complexity of the code is O(1).

This will output The next character after M is N. Note that this approach will only work for ASCII letters and will not work for other characters or non-ASCII letters.

 



Similar Reads

Ways to increment Iterator from inside the For loop in Python
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let's see with the help of the below
2 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 min read
Python | Insert character after every character pair
Sometimes, we can have a problem in which we need to insert a specific character after a pair(second) characters using Python. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in the Machine Learning domain. Let's discuss certain ways in which this problem can be solved.
6 min read
Python | Increment 1's in list based on pattern
Given a list of binary numbers 0 and 1, Write a Python program to transform the list in such a way that whenever 1 appears after the occurrence of a sequence of 0's, increment it by n+1, where 'n' is the last increment. Examples: Input : [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1] Output : [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3] Input : [1, 0, 1, 0, 0, 0, 1,
2 min read
Python | Increment value in dictionary
Sometimes, while working with dictionaries, we can have a use-case in which we require to increment a particular key's value in dictionary. It may seem quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Let's discuss certain ways in which this task can be performed. Met
6 min read
Specifying the increment in for-loops in Python
Let us see how to control the increment in for-loops in Python. We can do this by using the range() function. range() function range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well
2 min read
Python - Iterate through list without using the increment variable
Python Lists is much like flexible size arrays, declared in other languages like vector in C++, array list in Java, etc. Lists are heterogeneous, making it the most effective feature in Python. Lists are mutable, and hence can be modified even after they have been formed. The most common approach is to iterate through a list using the increment var
2 min read
Python program to Increment Suffix Number in String
Given a String, the task is to write a Python program to increment the number which is at end of the string. Input : test_str = 'geeks006' Output : geeks7 Explanation : Suffix 006 incremented to 7. Input : test_str = 'geeks007' Output : geeks8 Explanation : Suffix 007 incremented to 8. Method #1 : Using findall() + join() + replace() In this, strat
5 min read
Python program to Increment Numeric Strings by K
Given the Strings list, write a Python program to increment strings that are numeric by K. Examples: Input : test_list = ["gfg", "234", "is", "98", "123", "best", "4"], K = 6 Output : ['gfg', '240', 'is', '104', '129', 'best', '10'] Explanation : 234, 98 and 4 are incremented by 6 in result. Input : test_list = ["gfg", "234", "is", "98", "123", "be
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg