Python | Get the numeric prefix of a given string

Python Methods and Functions | String Variables

Method # 1: Using re.findall()
A regex can be used to accomplish this particular task. In this we use the findall function, which we use to get all occurrences of numbers and then return the starting occurrence.

# Python3 demo code
# Get numeric string prefix
# Using re.findall ()

import re

 
# initialization string

test_str = "1234Geeks"

 
# print the original string

print ( "The original string is : " test_str)

 
# Using re.findall ()
# Get numeric string prefix

res = re.findall ( 'd +' , test_str)

 
# print result

print ( "The prefix number at string:" + str (res [ 0 ]))

Output:

 The original string is: 1234Geeks The prefix number at string: 1234 

Method # 2: Using itertools.takewh ile ()
The built-in takewhile function can be used to perform this specific task of extracting all numbers before a character appears.

# Python3 code to demonstrate how it works
# Get the numeric string prefix
# Using itertools.takewhile ()

from itertools import takewhile

 
# initializing string

test_str = "1234Geeks"

 
# print original line

prin t ( "The original string is:" + test_str)

 
# Using itertools. takewhile ()
# Get numeric string prefix

res = '' .join (takewhile ( str .isdigit, test_str))

 
# print result

print ( "The prefix number at string:" + str (res))

Output:

 The original string is: 1234Geeks The prefix number at string: 1234 




Get Solution for free from DataCamp guru