0 votes
1 view
in Python by (15k points)

I would extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the isdigit() method?

Example:

line = "hello 12 hi 89"

Result:

[12, 89]

1 Answer

0 votes
by (33.8k points)

Actually, both regular expression and isdigit() method are good at their own place but I would suggest you use isdigit()but if you are not comfortable writing complex regular expression’s code then you should go for isdigit() method. Here’s an explanation of how regular expression and isdigit() method works:-

 

The reason why you should use isdigit():-

  1. The first reason is you need not to import any extra module for using isdigit() method.

  2. The second reason is regular expression is more  complex while writing the code.

  3. Last but not the least isdigit() looks more Pythonic then regular expression.

How regular expression works:-

import re

re.findall(r'\d+', 'hello 12 hi 89')

image

How the isdigit() method works:-

str = "hello 12 hi 89"

[int(s) for s in str.split() if s.isdigit()]

image

...