Python | Get the numeric prefix of given string
Last Updated :
08 Apr, 2023
Given a string. the task is to print numeric prefix in string (if it is present in string). Given below are few methods to solve the task.
Method #1: Using Naive Method
Python3
# Python code to demonstrate
# to get numeric prefix in string
# if present
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
# code to find numeric prefix in string
res1 = ''.join(c for c in ini_string if c in '0123456789')
res2 = ''.join(c for c in ini_string2 if c in '0123456789')
# printing resultant string
print ("first string result: ", str(res1))
print ("second string result: ", str(res2))
Output:initial string : 123abcjw abceddfgh
first string result: 123
second string result:
Time Complexity: O(n + m), where n + m are the length of given strings
Auxiliary Space: O(n + m)
Method #2: Using takewhile
Python3
# Python code to demonstrate
# to get numeric prefix in string
# if present
from itertools import takewhile
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
# code to find numeric prefix in string
res1 = ''.join(takewhile(str.isdigit, ini_string))
res2 = ''.join(takewhile(str.isdigit, ini_string2))
# printing resultant string
print ("first string result: ", res1)
print ("second string result: ", res2)
Output:initial string : 123abcjw abceddfgh
first string result: 123
second string result:
Time complexity: O(n), where n is the length of the string, since the code uses a for loop to iterate through the string and calls the built-in method str.isdigit() for each character in the string.
Auxiliary space: O(m), where m is the length of the numeric prefix in the string.
Method #3: Using re.sub
Python3
# Python code to demonstrate
# to get numeric prefix in string
# if present
import re
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
# code to find numeric prefix in string
res1 = re.sub('\D.*', '', ini_string)
res2 = re.sub('\D.*', '', ini_string2)
# printing resultant string
print ("first string result: ", str(res1))
print ("second string result: ", str(res2))
Output:initial string : 123abcjw abceddfgh
first string result: 123
second string result:
Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(1).
Using Method #4: Using re.findall
Python3
# Python code to demonstrate
# to get numeric prefix in string
# if present
import re
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
# code to find numeric prefix in string
res1 = ''.join(re.findall('\d+', ini_string))
res2 = ''.join(re.findall('\d+', ini_string2))
# printing resultant string
print ("first string result: ", str(res1))
print ("second string result: ", str(res2))
Output:initial string : 123abcjw abceddfgh
first string result: 123
second string result:
Time complexity: The time complexity of this program is O(n), where n is the length of the input string. The reason is that we perform a single pass over the string to extract the numeric prefix using the re.findall() function.
Auxiliary space: The auxiliary space used by this program is O(1), as we only use a few variables to store the input string, the regex pattern, and the extracted numeric prefix. The space used by these variables does not depend on the length of the input string. Therefore, the space complexity is constant.
Method #5: Using isalpha() method
Python3
# Python code to demonstrate
# to get numeric prefix in string
# if present
def fun(s):
x=""
for i in s:
if i.isalpha():
break
else:
x+=i
return x
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
# code to find numeric prefix in string
res1 = fun(ini_string)
res2 = fun(ini_string2)
# printing resultant string
print ("first string result: ", res1)
print ("second string result: ", res2)
Outputinitial string : 123abcjw abceddfgh
first string result: 123
second string result:
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #6: Using re.search()
In the above code, we are using the search function from the re module to find the longest prefix of numeric characters in the input string. The regular expression r'^\d+' matches one or more digits at the beginning of the string (the ^ symbol represents the start of the string).
If a match is found, the search function returns a Match object representing the match. We can use the group method of this object to extract the matched string. If no match is found, search returns None, and we return an empty string instead.
Finally, we use the print function to output the resulting prefix for each example input string.
Python
import re
def get_numeric_prefix(s):
"""
Extracts the numeric prefix from a string.
"""
# Use a regular expression to match the longest prefix of numeric characters
match = re.search(r'^\d+', s)
if match:
# Return the matched prefix
return match.group()
else:
# If no match was found, return an empty string
return ""
# Example usage
print(get_numeric_prefix("123abcjw"))
print(get_numeric_prefix("abceddfgh"))
print(get_numeric_prefix("123abcjw12"))
#This code is contributed by Edula Vinay Kumar Reddy
Time Complexity O(n), where n is the length of the input string.
Auxiliary Space: O(n).
Similar Reads
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
Python - Get Nth word in given String Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which thi
4 min read
Sort given list of strings by part the numeric part of string - Python We are given a list of strings containing both letters and numbers, and the goal is to sort them based on the numeric part within each string. To do this, we extract the digits, convert them to integers and use them as sorting keys. For example, in ["Gfg34", "is67", "be3st"], the numbers 34, 67, and
3 min read
Print Substrings that are Prefix of the Given String - Python The task of printing the substrings that are prefixes of a given string involves generating all the possible substrings that start from the first character of the string and end at any subsequent position.For example, if the given string is s = "hello", the prefixes of the string would include "h",
3 min read
Python | Get the string after occurrence of given substring The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python.Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read