Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove dot at the end of number

Tags:

python

I have a txt file that looks like this:

  1,           0.,           0.,           0.
  2,           0.,           0.,         600.
  3,           0.,           0.,        2600.
  4,           0.,           0.,          50.

I'd like to read it and create the following list:

['1', '0', '0', '0']
['2', '0', '0', '600']
['3', '0', '0', '2600']
['4', '0', '0', '50']

However I only manage to obtain:

['1', '0.', '0.', '0.']
['2', '0.', '0.', '600.']
['3', '0.', '0.', '2600.']
['4', '0.', '0.', '50.']

My code looks like:

for line in inputFile:
    fileData.append([x.strip() for x in line.split(',')])

EDIT: How can I convert my list of strings into a list of integers? tried some variations using the line of code I wrote above but couldn't make it.

like image 806
jpcgandre Avatar asked Nov 21 '25 17:11

jpcgandre


2 Answers

Pass "." + string.whitespace to strip so that it strips both the spaces and the periods:

from string import whitespace
for line in inputFile:
    fileData.append([int(x.strip("." + whitespace)) for x in line.split(',')])
like image 128
David Robinson Avatar answered Nov 23 '25 06:11

David Robinson


for line in inputFile:
    fileData.append([int(x.strip().rstrip('.')) for x in line.split(',')])

Instead of x.strip().rstrip('.'), you could use x.strip(' \t\r\n.'), but I think it is cleaner to let x.strip() handle all of the whitespace.

like image 40
Andrew Clark Avatar answered Nov 23 '25 06:11

Andrew Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!