Hướng dẫn re get numbers python

This is more than a bit late, but you can extend the regex expression to account for scientific notation too.

import re

# Format is [(, ), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
       ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
      ('hello X42 I\'m a Y-32.35 string Z30',
       ['42', '-32.35', '30']),
      ('he33llo 42 I\'m a 32 string -30', 
       ['33', '42', '32', '-30']),
      ('h3110 23 cat 444.4 rabbit 11 2 dog', 
       ['3110', '23', '444.4', '11', '2']),
      ('hello 12 hi 89', 
       ['12', '89']),
      ('4', 
       ['4']),
      ('I like 74,600 commas not,500', 
       ['74,600', '500']),
      ('I like bad math 1+2=.001', 
       ['1', '+2', '.001'])]

for s, r in ss:
    rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
    if rr == r:
        print('GOOD')
    else:
        print('WRONG', rr, 'should be', r)

Gives all good!

Additionally, you can look at the AWS Glue built-in regex

This is more than a bit late, but you can extend the regex expression to account for scientific notation too.

Nội dung chính

  • 1. Making use of isdigit() function to extract digits from a Python string
  • 2. Using regex library to extract digits
  • How do you select only numeric values in a string in Python?
  • How do you find the numeric value in Python?
  • How do I extract numbers from a string in Python?
  • How do I print only numbers in Python list?

import re

# Format is [(, ), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
       ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
      ('hello X42 I\'m a Y-32.35 string Z30',
       ['42', '-32.35', '30']),
      ('he33llo 42 I\'m a 32 string -30', 
       ['33', '42', '32', '-30']),
      ('h3110 23 cat 444.4 rabbit 11 2 dog', 
       ['3110', '23', '444.4', '11', '2']),
      ('hello 12 hi 89', 
       ['12', '89']),
      ('4', 
       ['4']),
      ('I like 74,600 commas not,500', 
       ['74,600', '500']),
      ('I like bad math 1+2=.001', 
       ['1', '+2', '.001'])]

for s, r in ss:
    rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
    if rr == r:
        print('GOOD')
    else:
        print('WRONG', rr, 'should be', r)

Gives all good!

Additionally, you can look at the AWS Glue built-in regex

Hello, readers! In this article, we will be focusing on the ways to extract digits from a Python String. So, let us get started.


1. Making use of isdigit() function to extract digits from a Python string

Python provides us with string.isdigit() to check for the presence of digits in a string.

Python isdigit() function returns True if the input string contains digit characters in it.

Syntax:

We need not pass any parameter to it. As an output, it returns True or False depending upon the presence of digit characters in a string.

Example 1:

inp_str = "Python4Journaldev"

print("Original String : " + inp_str) 
num = ""
for c in inp_str:
    if c.isdigit():
        num = num + c
print("Extracted numbers from the list : " + num) 

In this example, we have iterated the input string character by character using a for loop. As soon as the isdigit() function encounters a digit, it will store it into a string variable named ‘num’.

Thus, we see the output as shown below–

Output:

Original String : Python4Journaldev
Extracted numbers from the list : 4

Now, we can even use Python list comprehension to club the iteration and idigit() function into a single line.

By this, the digit characters get stored into a list ‘num’ as shown below:

Example 2:

inp_str = "Hey readers, we all are here be 4 the time!"


print("Original string : " + inp_str) 


num = [int(x) for x in inp_str.split() if x.isdigit()] 

 
print("The numbers list is : " + str(num)) 

Output:

Original string : Hey readers, we all are here be 4 the time!
The numbers list is : [4]

2. Using regex library to extract digits

Python regular expressions library called ‘regex library‘ enables us to detect the presence of particular characters such as digits, some special characters, etc. from a string.

We need to import the regex library into the python environment before executing any further steps.

Further, we we re.findall(r'\d+', string) to extract digit characters from the string. The portion ‘\d+’ would help the findall() function to detect the presence of any digit.

Example:

import re
inp_str = "Hey readers, we all are here be 4 the time 1!"


print("Original string : " + inp_str) 

num = re.findall(r'\d+', inp_str) 

print(num)

So, as seen below, we would get a list of all the digit characters from the string.

Output:

Original string : Hey readers, we all are here be 4 the time 1!
['4', '1']

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

I recommend you all to try implementing the above examples using data structures such as lists, dict, etc.

For more such posts related to Python, Stay tuned and till then, Happy Learning!! 🙂

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let’s discuss certain ways in which this problem can be solved.

    Method #1 : Using List comprehension + isdigit() + split()
    This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.

    test_string = "There are 2 apples for 4 persons"

    print("The original string : " + test_string)

    res = [int(i) for i in test_string.split() if i.isdigit()]

    print("The numbers list is : " + str(res))

    Output :

    The original string : There are 2 apples for 4 persons
    The numbers list is : [2, 4]
    

    Method #2 : Using re.findall()
    This particular problem can also be solved using python regex, we can use the findall function to check for the numeric occurrences using matching regex string.

    import re

    test_string = "There are 2 apples for 4 persons"

    print("The original string : " + test_string)

    temp = re.findall(r'\d+', test_string)

    res = list(map(int, temp))

    print("The numbers list is : " + str(res))

    Output :

    The original string : There are 2 apples for 4 persons
    The numbers list is : [2, 4]
    

    How do you select only numeric values in a string in Python?

    Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

    How do you find the numeric value in Python?

    A random float r, above 0 and below 1. x rounded to n digits from the decimal point. Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. ... Basics..

    How do I extract numbers from a string in Python?

    How to extract integers from a string in Python.

    a_string = "0abc 1 def 23".

    numbers = [].

    for word in a_string. split():.

    if word. isdigit():.

    numbers. append(int(word)).

    print(numbers).

    How do I print only numbers in Python list?

    “how to extract numbers from a list in python” Code Answer.

    a = ['1 2 3', '4 5 6', 'invalid'].

    numbers = [].

    for item in a:.

    for subitem in item. split():.

    if(subitem. isdigit()):.

    numbers. append(subitem).

    print(numbers).