JoJo
JoJo

Reputation: 23

Separate float into digits

I have a float:

pi = 3.141

And want to separate the digits of the float and put them into a list as intergers like this:

#[3, 1, 4, 1]

I know to to separate them and put them into a list but as strings and that doesnt help me

Upvotes: 2

Views: 1997

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52081

You need to loop through the string representation of the number and check if the number is a digit. If yes, then add it to the list. This can be done by using a list comprehension.

>>> pi = 3.141
>>> [int(i) for i in str(pi) if i.isdigit()]
[3, 1, 4, 1]

Another way using Regex (Not - preffered)

>>> map(int,re.findall('\d',str(pi)))
[3, 1, 4, 1]

A final way - Brute force

>>> pi = 3.141
>>> x = list(str(pi))
>>> x.remove('.')
>>> map(int,x)
[3, 1, 4, 1]

Few references from the docs

The timeit results

python -m timeit "pi = 3.141;[int(i) for i in str(pi) if i.isdigit()]"
100000 loops, best of 3: 2.56 usec per loop
python -m timeit "s = 3.141; list(map(int, str(s).replace('.','')))" # Avinash's Method
100000 loops, best of 3: 2.54 usec per loop
python -m timeit "import re;pi = 3.141; map(int,re.findall('\d',str(pi)))"
100000 loops, best of 3: 5.72 usec per loop
python -m timeit "pi = 3.141; x = list(str(pi));x.remove('.'); map(int,x);"
100000 loops, best of 3: 2.48 usec per loop

As you can see the brute force method is the fastest. The Regex answer as known is the slowest.

Upvotes: 7

Avinash Raj
Avinash Raj

Reputation: 174706

You could also use string.replace along with map, list functions.

>>> s = 3.141
>>> list(map(int, str(s).replace('.','')))
[3, 1, 4, 1]

Upvotes: 5

Related Questions