Python Get the numeric prefix of given string


Suppose we have a string which contains numbers are the beginning. In this article we will see how to get only the numeric part of the string which is fixed at the beginning.

With isdigit

The is digit function decides if the part of the string is it digit or not. So we will use takewhile function from itertools to join each part of the string which is a digit.

Example

 Live Demo

from itertools import takewhile
# Given string
stringA = "347Hello"
print("Given string : ",stringA)
# Using takewhile
res = ''.join(takewhile(str.isdigit, stringA))
# printing resultant string
print("Numeric Pefix from the string: \n", res)

Output

Running the above code gives us the following result −

Given string : 347Hello
Numeric Pefix from the string:
347

with re.sub

Using the regular expression module re we can create a pattern to search for the digits only. The search will only find the digits at the beginning of the string.

Example

 Live Demo

import re
# Given string
stringA = "347Hello"
print("Given string : ",stringA)
# Using re.sub
res = re.sub('\D.*', '', stringA)
# printing resultant string
print("Numeric Pefix from the string: \n", res)

Output

Running the above code gives us the following result −

Given string : 347Hello
Numeric Pefix from the string:
347

With re.findall

The findall function works in a similar manner as a girl accept that we use a plus sign instead of *.

Example

 Live Demo

import re
# Given string
stringA = "347Hello"
print("Given string : ",stringA)
# Using re.sub
res = ''.join(re.findall('\d+',stringA))
# printing resultant string
print("Numeric Pefix from the string: \n", res)

Output

Running the above code gives us the following result −

Given string : 347Hello
Numeric Pefix from the string:
347

Updated on: 09-Jul-2020

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements