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 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 ])) |
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.
# 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)) |
The original string is : 1234Geeks The prefix number at string : 1234
Recommended Posts:
- Python | Get the numeric prefix of given string
- Python | Check if given string is numeric or not
- Python | Check Numeric Suffix in String
- Python | Ways to remove numeric digits from given string
- Python Regex to extract maximum numeric value from a string
- Python | Convert numeric String to integers in mixed List
- Python program to print the substrings that are prefix of the given string
- Python | Sort numeric strings in a list
- Python | Add only numeric values present in a list
- Find the longest common prefix between two strings after performing swaps on second string
- Python | Prefix sum list
- Python | Prefix key match in dictionary
- Python | Prefix extraction before specific character
- Prefix matching in Python using pytrie module
- Python | Remove prefix strings from list
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.