Processing user input often involves cleaning unstructured text to extract specific data types, such as integers. While you could iterate through characters manually, Python's re (Regular Expression) module provides a much more efficient and readable solution.
This guide explains how to use regular expressions to find, extract, and format integers from any given string.
Understanding the Regex Pattern
To extract numbers from mixed text (e.g., "Item 12 costs $50"), we need a pattern that identifies digits.
\d: Matches any decimal digit (0-9).+: Quantifier meaning "one or more" of the preceding element.
Therefore, the pattern r"\d+" matches sequences of one or more digits.
Step 1: Setting Up the Script
Regular expressions are not loaded by default. You must import the standard re module.
Create a file named find_int.py and add the import statement.
import reStep 2: Implementing Extraction Logic
We use re.findall() to locate all non-overlapping matches of the pattern in the string. It returns a list of strings.
import re
text = "Order ID: 5592, Qty: 3"
digits = []
temp = ""
for char in text:
if char.isdigit():
temp += char
else:
if temp: digits.append(temp)
temp = ""
integers = re.findall(r"\d+", text)Step 3: Handling Input and Output
The goal is to return a space-separated string of numbers found in the input.
def extract_integers(user_input):
integers_list = re.findall(r"\d+", user_input)
return " ".join(integers_list)Complete Code Solution
Here is the complete find_int.py script. It accepts input from the command line (standard input) and prints the extracted numbers.
import re
def extract_integers(user_input):
"""
Finds all integers in a string and returns them as a space-separated string.
"""
integers = re.findall(r"\d+", user_input)
return " ".join(integers)
if __name__ == "__main__":
try:
user_text = input()
result = extract_integers(user_text)
print(result)
except EOFError:
pass # Handle cases where input might be empty/closed abruptlyTesting the Script
Test Case 1
Input: a1b2c3d4
$ python find_int.py
a1b2c3d4Output:
1 2 3 4Test Case 2
Input: 12 3ad5
$ python find_int.py
12 3ad5Output:
12 3 5Conclusion
Regular expressions are the most robust tool for text parsing in Python.
- Import
reto access regex tools. - Use
r"\d+"to match whole integers (sequences of digits). - Use
re.findall()to extract all occurrences into a list. - Use
join()to format the output list back into a string.