Python program to Increment Suffix Number in String
Last Updated :
25 Feb, 2023
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, strategy we perform the task of finding number using findall(), then perform the task of separating numeric string and prefix string, then an increment of a numeric string is performed. At last, the string is joined to get a prefix followed by an incremented number.
Python3
# Python3 code to demonstrate working of
# Increment Suffix Number
# Using findall() + join() + replace()
import re
# initializing string
test_str = 'geeks006'
# printing original string
print("The original string is : " + str(test_str))
# getting suffix number
reg = re.compile(r'[ 0 - 9]')
mtch = reg.findall(test_str)
# getting number
num = ''.join(mtch[-3 : ])
pre_str = test_str.replace(num, '')
# Increment number
add_val = int(num) + 1
# joining prefix str and added value
res = pre_str + str(add_val)
# printing result
print("Incremented numeric String : " + str(res))
Output:
The original string is : geeks006
Incremented numeric String : geeks61
Method #2 : Using sub() + group() + zfill()
In this, we perform the task of grouping numbers using group() and incrementing, zfill() is used for task of filling the required leading values in numerical. The sub() is used to find the numerical part of strings.
Python3
# Python3 code to demonstrate working of
# Increment Suffix Number
# Using sub() + group() + zfill()
import re
# initializing string
test_str = 'geeks006'
# printing original string
print("The original string is : " + str(test_str))
# fstring used to form string
# zfill fills values post increment
res = re.sub(r'[0-9]+$',
lambda x: f"{str(int(x.group())+1).zfill(len(x.group()))}",
test_str)
# printing result
print("Incremented numeric String : " + str(res))
Output:
The original string is : geeks006
Incremented numeric String : geeks007
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Method #3 : Using string slicing and addition
Python3
# initializing string
test_str = 'geeks006'
# printing original string
print("The original string is : " + str(test_str))
suffix = int(test_str[-3:])
prefix = test_str[:-3]
# Increment number
suffix += 1
# joining prefix str and added value
res = prefix + str(suffix).zfill(3)
# printing result
print("Incremented numeric String : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original string is : geeks006
Incremented numeric String : geeks007
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using isalpha(),replace() and slicing
Python3
# Python3 code to demonstrate working of
# Increment Suffix Number
# initializing string
test_str = 'geeks006'
# printing original string
print("The original string is : " + str(test_str))
x=test_str[::-1]
res=""
for i in x:
if i.isalpha():
break
else:
res+=i
res=res[::-1]
x=int(res)+1
test_str=test_str.replace(res,"")
test_str+=str(x)
# printing result
print("Incremented numeric String : " + str(test_str))
OutputThe original string is : geeks006
Incremented numeric String : geeks7
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#5: Using Recursive method.
Here is the step-by-step algorithm for this code:
- Define a function increment_suffix(s) that takes in a string s, and increments the numeric suffix at the end of the string by 1.
- Check for the base case where the input string is empty. If the string is empty, return the string "1" to indicate that the suffix is 0.
- For the recursive case, check whether the last character in the string is a digit by calling the isdigit() string method.
- If the last character is a digit, compute the carry by adding 1 to the integer value of the last character, and then dividing by 10 to get the carry digit. The carry is added to the result of a recursive call to increment_suffix() on the substring s[:-1]. The incremented suffix digit is obtained by taking the sum of the last character and the carry, modulo 10.
- If the last character is not a digit, simply return the input string s.
- In the main code, initialize the test string test_str.
- Call the increment_suffix() function on the substring test_str[:-3] to get the incremented suffix without the last three digits. The last three digits are extracted from the original test_str using string slicing, and are incremented by 1 using integer addition. The zfill() method is then called on the resulting integer to ensure that it has three digits.
- Concatenate the result of the recursive call to increment_suffix() with the incremented suffix digits, and print the result.
Python3
# Python3 code to demonstrate working of
# Increment Suffix Number
def increment_suffix(s):
if not s:
return '1'
if s[-1].isdigit():
carry = (int(s[-1]) + 1) // 10
return increment_suffix(s[:-1]) + str((int(s[-1]) + carry) % 10)
return s
# initializing string
test_str = 'geeks006'
# printing original string
print("The original string is : " + str(test_str))
res=increment_suffix(test_str[:-3]) + str(int(test_str[-3:]) + 1).zfill(3)
# printing result
print("Incremented numeric String : " + str(res))
#this code contributed by tvsk
OutputThe original string is : geeks006
Incremented numeric String : geeks007
The time complexity of this method is O(n), where n is the length of the input string, because it processes each character of the string at most once. The worst-case time complexity occurs when the suffix has many digits, in which case the method makes many recursive calls. The best-case time complexity occurs when the suffix has only one digit, in which case the method makes only one call to increment_suffix().
The space complexity of this method is O(n), because it creates a new stack frame for each recursive call, which requires additional memory on the call stack. However, the maximum depth of the call stack is equal to the length of the input string, so the space complexity is proportional to the size of the input.
Similar Reads
Python program to extract numeric suffix from string
Given a string of characters with digits embedded in it. The task is to write a Python program to extract all the numbers that are trailing, i.e at the suffix of the string. Examples:Input : test_str = "GFG04"Output : 04Explanation : 04 is suffix of string and number hence extracted.Input : test_str
7 min read
Python Program to move numbers to the end of the string
Given a string, the task is to write a Python program to move all the numbers in it to its end. Examples: Input : test_str = 'geek2eeks4g1eek5sbest6forall9' Output : geekeeksgeeksbestforall241569 Explanation : All numbers are moved to end. Input : test_str = 'geekeeksg1eek5sbest6forall9' Output : ge
6 min read
Increment Numeric Strings by K - Python
Given the Strings list we have to increment numeric strings in a list by a given integer K. ( Note that strings that are not numeric remain unchanged ) For example: In the list ["gfg", "234", "is", "98", "123", "best", "4"] if K = 6 then result will be ["gfg", "240", "is", "104", "129", "best", "10"
4 min read
Python Program to Group Strings by K length Using Suffix
Given Strings List, the task is to write a Python program to group them into K-length suffixes. Input : test_list = ["food", "peak", "geek", "good", "weak", "sneek"], K = 3 Output : {'ood': ['food', 'good'], 'eak': ['peak', 'weak'], 'eek': ['geek', 'sneek']} Explanation : words ending with ood are f
5 min read
Python | Check Numeric Suffix in String
Sometimes, while programming, we can have such a problem in which we need to check if any string is ending with a number i.e it has a numeric suffix. This problem can occur in Web Development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using regex This problem
6 min read
Insert a number in string - Python
We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Python - Ways to Count Number of Substring in String
Given a string s, determine the number of substrings that satisfy certain criteria. For example we are given a string s="hellohellohello" we need to count how many time the substring occur in the given string suppose we need to find the substring "hello" so that the count becomes 3. We can use metho
2 min read
Python program to find Indices of Overlapping Substrings
To count the number of overlapping sub-strings in Python we can use the Re module. To get the indices we will use the re.finditer() method. But it returns the count of non-overlapping indices only. Examples: Input: String: "geeksforgeeksforgeeks" ; Pattern: "geeksforgeeks" Output: [0, 8] Explanation
4 min read
Python | Append suffix/prefix to strings in list
Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let's discuss a way in which this task can be performed. Method #1: Using + o
5 min read
Python Program to Reverse a Number
We are given a number and our task is to reverse its digits. For example, if the input is 12345 then the output should be 54321. In this article, we will explore various techniques for reversing a number in Python. Using String SlicingIn this example, the Python code reverses a given number by conve
3 min read