Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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

Related questions

0 votes
1 answer
asked Oct 17, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

Browse Categories

...