Python | Get numeric prefix of given string
Sometimes, while working with strings, we might be in a situation in which we require to get the numeric prefix of a string. This kind of application can come in various domains such as web application development. Let’s discuss certain ways in which this task can be performed.
Method #1: Using re.findall() The regex can be used to perform this particular task. In this, we use findall() function which we use to get all the occurrences of numbers and then return the initial occurrence.
Python3
# Python3 code to demonstrate working of# Get numeric prefix of string# Using re.findall()import re# initializing stringtest_str = "1234Geeks"# printing original stringprint("The original string is : " + test_str)# Using re.findall()# Get numeric prefix of stringres = re.findall('\d+', test_str)# printing resultprint("The prefix number at string : " + str(res[0])) |
The original string is : 1234Geeks The prefix number at string : 1234
The time complexity of this code is O(n), where n is the length of the string “test_str”. The function “re.findall()” iterates over the string “test_str” once to find all occurrences of the pattern ‘\d+’ (a sequence of one or more digits).
The space complexity of this code is O(n), where n is the length of the prefix number found in “test_str”. The function “re.findall()” stores the result in a list, which takes up space proportional to the length of the prefix number.
Method #2: Using itertools.takewhile() The inbuilt function of takewhile can be used to perform this particular task of extracting all the numbers till a character occurs.
Python3
# Python3 code to demonstrate working of# Get numeric prefix of string# Using itertools.takewhile()from itertools import takewhile# initializing stringtest_str = "1234Geeks"# printing original stringprint("The original string is : " + test_str)# Using itertools.takewhile()# Get numeric prefix of stringres = ''.join(takewhile(str.isdigit, test_str))# printing resultprint("The prefix number at string : " + str(res)) |
The original string is : 1234Geeks The prefix number at string : 1234
Method #3: Using isdigit() method
Python3
# Python3 code to demonstrate working of# Get numeric prefix of string# initializing stringtest_str = "1234Geeks"# printing original stringprint("The original string is : " + test_str)s=""for i in test_str: if(i.isdigit()): s+=i else: break# printing resultprint("The prefix number at string : " + str(s)) |
The original string is : 1234Geeks The prefix number at string : 1234






Please Login to comment...