Python Forum
Remove \n at the end of a character from a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Remove \n at the end of a character from a list (/thread-19330.html)



Remove \n at the end of a character from a list - judkil - Jun-23-2019

Hi !

After getting a series of numbers in a text file via the command with open, I end up with the following list:

['13.5\n', '17\n', '9.5\n', '12\n', '14\n', '6\n', '5.5\n', '8.5\n', '10.5\n', '29\n', '14\n', '9\n', '15.5\n', '11.5\n', '16\n', '18\n', '13\n', '12.5\n', '15.5\n']


Info: I use python 3

There I block, because I will like to remove all the "\ n" in order to be able to pass them in float in a new list.

If someone has an idea thank you very much!


RE: Remove \n at the end of a character from a list - metulburr - Jun-24-2019

>>> lst = ['13.5\n', '17\n', '9.5\n', '12\n', '14\n', '6\n', '5.5\n', '8.5\n', '10.5\n', '29\n', '14\n', '9\n', '15.5\n', '11.5\n', '16\n', '18\n', '13\n', '12.5\n', '15.5\n']
>>> lst = [e.strip() for e in lst]
>>> lst
['13.5', '17', '9.5', '12', '14', '6', '5.5', '8.5', '10.5', '29', '14', '9', '15.5', '11.5', '16', '18', '13', '12.5', '15.5']
>>> lst = [float(e.strip()) for e in lst]
>>> lst
[13.5, 17.0, 9.5, 12.0, 14.0, 6.0, 5.5, 8.5, 10.5, 29.0, 14.0, 9.0, 15.5, 11.5, 16.0, 18.0, 13.0, 12.5, 15.5]



RE: Remove \n at the end of a character from a list - DeaD_EyE - Jun-24-2019

You don't need to strip whitespaces, if you use float. Same for int.