Python Get the numeric prefix of given string

Sometimes we need to extract the numeric prefix from a string that contains numbers at the beginning. Python provides several approaches to extract only the numeric part from the start of a string.

Using takewhile() with isdigit()

The isdigit() method checks if each character is a digit. Combined with takewhile() from itertools, we can extract consecutive digits from the beginning ?

from itertools import takewhile

# Given string
string_data = "347Hello"
print("Given string:", string_data)

# Using takewhile with isdigit
result = ''.join(takewhile(str.isdigit, string_data))

print("Numeric prefix from the string:", result)

The output of the above code is ?

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

Using re.sub() Pattern Replacement

Regular expressions can remove non-digit characters after the initial numeric sequence. The pattern \D.* matches any non-digit followed by any characters ?

import re

# Given string
string_data = "347Hello"
print("Given string:", string_data)

# Using re.sub to remove non-digits after initial digits
result = re.sub(r'\D.*', '', string_data)

print("Numeric prefix from the string:", result)

The output of the above code is ?

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

Using re.match() for Exact Prefix

The match() function specifically looks for patterns at the beginning of a string, making it ideal for extracting numeric prefixes ?

import re

# Given string
string_data = "347Hello"
print("Given string:", string_data)

# Using re.match to find digits at start
match = re.match(r'\d+', string_data)
result = match.group() if match else ''

print("Numeric prefix from the string:", result)

The output of the above code is ?

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

Comparison of Methods

Method Import Required Best For
takewhile() itertools Simple character-by-character processing
re.sub() re Pattern replacement approach
re.match() re Explicit prefix matching

Conclusion

Use takewhile() for simple digit extraction without regex complexity. Use re.match() when you specifically want to match patterns at the string beginning.

Updated on: 2026-03-15T18:11:22+05:30

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements