This tutorial will guide you through the process of extracting numbers from a word in Python. Python is a high-level and general-purpose programming language.
Known for its simplicity, Python increases productivity by emphasizing readability and reducing program maintenance costs. Python provides multiple methods for string manipulation and we will be using these built-in functions to achieve our goal.
Step 1: Understanding the Process
The first thing we need to understand is what exactly we are doing here: we want to extract all the numbers from a given string in Python. So, if our string is something like ‘alpha123beta456’, we want to be able to get ‘123456’ as our output.
Step 2: Using Regular Expressions
Regular Expressions (RegEx) are incredibly powerful for manipulating text data. Python’s in-built re module allows us to use RegEx in our Python programs. We will be using the re.findall() method, which returns a list containing all matches. The syntax is: re.findall(pattern, string, flags=0). Also, we will be using the pattern ‘\d+’, which matches any digit (equivalent to [0-9]).
1 2 3 4 5 |
import re sequence = 'alpha123beta456' numbers = re.findall('\d+', sequence) print(numbers) |
Step 3: Turning the List into a String
The output of the previous step is a list of strings. However, what we want is a single string. So, we will use the join() function to concatenate all the strings in the list into one string.
1 2 |
output = ''.join(numbers) print(output) |
Step 4: Converting String to Integer
If you require the output as an integer, we can easily convert the string to an integer using the int() function.
1 2 |
output = int(output) print(output) |
Displaying the Full Code
1 2 3 4 5 6 7 8 9 10 |
import re sequence = 'alpha123beta456' numbers = re.findall('\d+', sequence) output = ''.join(numbers) print('The numbers in the sequence:', output) output = int(output) print('The numbers converted to integer:', output) |
Conclusion
In this tutorial, we learned how to extract numbers from a string using Python. We used both built-in Python functions and the regular expression module.
Regular expressions are incredibly powerful for text manipulation tasks and are a useful tool for any Python programmer to understand. Python’s inherent readability and simplicity make such tasks simple and efficient. Happy coding!