mdivk
mdivk

Reputation: 3727

How to check and extract only numbers from a string with python

I have a dynamically generated string like:

'\n\n\n0\n1\n\n\n\n\n\n'
or 
'\r\n\r\n\r\n0\r\n\r\n1\r\n\r\n'
or 
'\r\n\r\n\r\n1/2\r\n\r\n1/2\r\n\r\n'

I wonder what is the best way to extract only the number 1, 0 or 1/2 with python 3

What I am doing now is use \r\n or \n to split the string and check each element in the list - I don't like my own way to process, there should be a better and elegant way to do that.

Thanks

Upvotes: 1

Views: 117

Answers (2)

Ragnar Moberg
Ragnar Moberg

Reputation: 1

It all can be done as a single one-liner using list-comprehension:

numbers=[float(i) for i in myString.split()]

The split method of the string class will take care of the excess whitespace for you.

Upvotes: 0

J_H
J_H

Reputation: 20505

Split on whitespace to retrieve words. Then turn each word into a number, a fraction. Then convert to floating point, in case you find that more convenient.

(No need to wrap it with list(), if you're happy with a generator.)

from fractions import Fraction

def get_nums(s):
    """Extracts fractional numbers from input string s."""
    return list(map(float, (map(Fraction, s.split()))))

Upvotes: 1

Related Questions