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
import re
test_str = 'geeks006'
print ( "The original string is : " + str (test_str))
reg = re. compile (r '[ 0 - 9]' )
mtch = reg.findall(test_str)
num = ''.join(mtch[ - 3 : ])
pre_str = test_str.replace(num, '')
add_val = int (num) + 1
res = pre_str + str (add_val)
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
import re
test_str = 'geeks006'
print ( "The original string is : " + str (test_str))
res = re.sub(r '[0-9]+$' ,
lambda x: f "{str(int(x.group())+1).zfill(len(x.group()))}" ,
test_str)
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
test_str = 'geeks006'
print ( "The original string is : " + str (test_str))
suffix = int (test_str[ - 3 :])
prefix = test_str[: - 3 ]
suffix + = 1
res = prefix + str (suffix).zfill( 3 )
print ( "Incremented numeric String : " + str (res))
|
Output
The original string is : geeks006
Incremented numeric String : geeks007
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using isalpha(),replace() and slicing
Python3
test_str = 'geeks006'
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)
print ( "Incremented numeric String : " + str (test_str))
|
Output
The 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
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
test_str = 'geeks006'
print ( "The original string is : " + str (test_str))
res = increment_suffix(test_str[: - 3 ]) + str ( int (test_str[ - 3 :]) + 1 ).zfill( 3 )
print ( "Incremented numeric String : " + str (res))
|
Output
The 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 count the number of characters in a String
The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this. Using len()len() i
3 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
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 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
Python program to calculate the number of digits and letters in a string
In this article, we will check various methods to calculate the number of digits and letters in a string. Using a for loop to remove empty strings from a list involves iterating through the list, checking if each string is not empty, and adding it to a new list. [GFGTABS] Python s = "Hello123!
3 min read
Python - Splitting Text and Number in string
Given a string containing both letters and numbers, the task is to separate the text (letters) and the numbers into two separate outputs. For example, if the input is "abc123", the output should be "abc" and "123". Let's discuss various ways in which we can achieve this in Python. Using for loopThis
3 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
2 min read
Python program to find the string weight
Given a String, each character mapped with a weight( number), compute the total weight of the string. Input : test_str = 'GeeksforGeeks', {"G" : 1, "e" : 2, "k" : 5, "f" : 3, "s" : 15, "o" : 4, "r" : 6} Output : 63 Explanation : 2 (G*2) + 8(e*4) + 30(s*2) + 10(k*2) + 4(o) + 6(r) +3(f) = 63.Input : t
4 min read