Python | Get the numeric prefix of given string
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
# Python code to demonstrate# to get numeric prefix in string# if present # initialising stringini_string = "123abcjw"ini_string2 = "abceddfgh" # printing string and its lengthprint ("initial string : ", ini_string, ini_string2) # code to find numeric prefix in stringres1 = ''.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 stringprint ("first string result: ", str(res1))print ("second string result: ", str(res2)) |
Output:
initial string : 123abcjw abceddfgh first string result: 123 second string result:
Method #2: Using takewhile
# Python code to demonstrate# to get numeric prefix in string# if presentfrom itertools import takewhile # initialising stringini_string = "123abcjw"ini_string2 = "abceddfgh" # printing string and its lengthprint ("initial string : ", ini_string, ini_string2) # code to find numeric prefix in stringres1 = ''.join(takewhile(str.isdigit, ini_string))res2 = ''.join(takewhile(str.isdigit, ini_string2)) # printing resultant stringprint ("first string result: ", res1)print ("second string result: ", res2) |
Output:
initial string : 123abcjw abceddfgh first string result: 123 second string result:
Method #3: Using re.sub
# Python code to demonstrate# to get numeric prefix in string# if presentimport re # initialising stringini_string = "123abcjw"ini_string2 = "abceddfgh" # printing string and its lengthprint ("initial string : ", ini_string, ini_string2) # code to find numeric prefix in stringres1 = re.sub('\D.*', '', ini_string)res2 = re.sub('\D.*', '', ini_string2) # printing resultant stringprint ("first string result: ", str(res1))print ("second string result: ", str(res2)) |
Output:
initial string : 123abcjw abceddfgh first string result: 123 second string result:
Using Method #4: Using re.findall
# Python code to demonstrate# to get numeric prefix in string# if presentimport re # initialising stringini_string = "123abcjw"ini_string2 = "abceddfgh" # printing string and its lengthprint ("initial string : ", ini_string, ini_string2) # code to find numeric prefix in stringres1 = ''.join(re.findall('\d+', ini_string))res2 = ''.join(re.findall('\d+', ini_string2)) # printing resultant stringprint ("first string result: ", str(res1))print ("second string result: ", str(res2)) |
Output:
initial string : 123abcjw abceddfgh first string result: 123 second string result:


