Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

The following lines are from my text from a .txt file:

 0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002     \n

I've been facing a problem on how to make this first line into a list. I've tried the line.strip() but that only took care of the first and last spaces. There are still spaces left that I couldn't get rid of. As seen below:

'0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002'

I also can't just replace all " " with " " as all numbers would get crumpled together. I also can't assume the number of whitespaces, nor the number of spaces before the ".", as I may have numbers greater than or equal to 10 down the line.

1 Answer

0 votes
by (36.8k points)
edited by

Use re.split.

Here is example.

a = '0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002'

import re

output = re.split(' +', a)

the output is

['0.14999999999999999',

 '0.20000000000000001',

 '0.29999999999999999',

 '0.34999999999999998',

 '0.50000000000000000',

 '0.59999999999999998',

 '0.69999999999999996',

 '0.72999999999999998',

 '0.84999999999999998',

 '0.90000000000000002'].

If you want every element in the output becomes float, then use the map.

output = list(map(float, output))

Do check out Python for data science course which helps you understand Python from scratch 

Related questions

Browse Categories

...