Extraction of Numbers from Strings in Python
Extracting numbers from a string can be achieved using either regular expressions or the isdigit() method. Let's compare the approaches to determine which is better suited for the purpose.
Regular Expressions
Regular expressions offer a powerful tool for matching patterns in strings. To extract numbers, you can use the following regular expression:
r'\d+'
This expression matches strings containing one or more decimal digits. For example, consider the string "hello 23 hi 33". The following code will use the regular expression to extract the numbers:
import re line = "hello 23 hi 33" result = re.findall(r'\d+', line) print(result) # [23, 33]
isdigit() Method
The isdigit() method is a simpler approach to test if a character is a decimal digit. However, it does not provide the ability to extract numbers as a whole. To use isdigit(), you would need to iterate through the string character by character:
line = "hello 23 hi 33" result = [] for char in line: if char.isdigit(): result.append(int(char)) print(result) # [2, 3, 3]
Comparison
Ultimately, the choice between regular expressions and the isdigit() method depends on the specific use case. Regular expressions provide more flexibility for complex pattern matching and extraction. They also support features like word boundaries (b) for matching numbers surrounded by whitespace.
For simple extraction of numbers from a string, the isdigit() method may be sufficient. However, for more complex cases or if extracting numbers as a whole is required, regular expressions offer a more comprehensive solution.
The above is the detailed content of Regex or `isdigit()`? Which is Best for Extracting Numbers from Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!