Python | Get the numeric prefix of a given string

Method # 1: Using the naive method

# Python code for demo
# to get the numeric prefix in the string
# if present

 
# initialization string

ini_string = " 123abcjw "

ini_string2 = "abceddfgh"

 
# print string and its length

print ( "initial string:" , ini_string, ini_string2)

  
# code to find a numeric prefix in a 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 `)

  

 
# print the resulting 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: 

Method # 2: Using takewhile

# Python code for demonstration
# to get a numeric prefix in line
# if present

from itertools import takewhile

  
# initializing string

ini_string = "123abcjw"

ini_string2 = " abceddfgh "

  
# print line and its length

print ( "initial string:" , ini_string, ini_string2)

 
# code to find a numeric prefix in a string

res1 = `` .join (takewhile ( str . isdigit, ini_string))

res2 = `` .join (takewhile ( str . isdigit, ini_string2))

  
# print the resulting string

print ( "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 for demonstration
# to get a numeric prefix in a string
# if submit

import re < / p>

 
# initialization string

ini_string = " 123abcjw "

ini_string2 = "abceddfgh"

 
# print string and its length

print ( "initial string:" , ini_string, ini_string2)

 
# code to find a numeric prefix in a string

res1 = re.sub ( ` D. * ` , ``, ini_string)

res2 =   re.sub ( `D. *` , ``, ini_string2)

 

 
# print the resulting string

print ( " first string result: " , str (res1))

print ( "second string result: " , str (res2))

Exit:

 initial string: 123abcjw abceddfgh first string result: 123 second string result: 

Using method # 4: Using re.findall

# Python code for demo
# to get a numeric prefix in a string
# if submitted

import re

  
# initialization string

ini_string = "123abcjw"

ini_string2 = "abceddfgh "

  
# print line and its length

print ( "initial string:" , ini_string, ini_string2)

 
# code to find a numeric prefix in a string

res1 = ` ` .join (re.findall (` d + `, ini_string))

res2 = ` ` .join (re.findall (` d + `, ini_string2))

 
# print the resulting string

print ( "first string result:" , str (res1))

print ( "second s tring result: " , str (res2))

Exit:

 initial string: 123abcjw abceddfgh first string result: 123 second string result: