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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get numeric prefix of string 
# Using re.findall()
import re
  
# initializing string 
test_str = "1234Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using re.findall()
# Get numeric prefix of string 
res = re.findall('\d+', test_str)
  
# printing result 
print("The prefix number at string : " + str(res[0]))

chevron_right


Output :



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

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get numeric prefix of string 
# Using itertools.takewhile()
from itertools import takewhile
  
# initializing string 
test_str = "1234Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using itertools.takewhile()
# Get numeric prefix of string 
res = ''.join(takewhile(str.isdigit, test_str))
  
# printing result 
print("The prefix number at string : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.