Home > Backend Development > Python Tutorial > Regex or `isdigit()`? Which is Best for Extracting Numbers from Strings in Python?

Regex or `isdigit()`? Which is Best for Extracting Numbers from Strings in Python?

Mary-Kate Olsen
Release: 2024-12-20 04:00:10
Original
319 people have browsed it

Regex or `isdigit()`? Which is Best for Extracting Numbers from Strings in Python?

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+'
Copy after login

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]
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template