简体   繁体   中英

Remove unwanted characters after using file.readlines()

I've tried using lines.split() and lines.strip() but could not manage to remove the following: ' ', \n or # .

>>> f = open('example.txt')
>>> lines = f.readlines()
>>> lines
['#\n', '2.1,-3.1\n', '-0.7,4.1\n', '#\n', '3.8,1.5\n', '-1.2,1.1']

Needing this output
[2.1, -3.1, -0.7, 4.1, 3.8, 1.5, -1.2, 1.1]

You can first remove the newlines. Then strip, clean based on the # character. The code is as follows:

a = [i.strip() for i in lines]
b = [float(j) for i in a for j in i.split(",") if "#" not in j]

The output is as follows:

>>> a
['#', '2.1,-3.1', '-0.7,4.1', '#', '3.8,1.5', '-1.2,1.1']
>>> b
[2.1, -3.1, -0.7, 4.1, 3.8, 1.5, -1.2, 1.1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM