Python Forum
Remove \n at the end of a character from a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Remove \n at the end of a character from a list
#1
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!
Reply
#2
>>> 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]
Reply
#3
You don't need to strip whitespaces, if you use float. Same for int.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Remove specific elements from list with a pattern Xalagy 3 271 Oct-11-2020, 07:18 AM
Last Post: Xalagy
  How to remove dict from a list? Denial 7 207 Sep-28-2020, 02:40 PM
Last Post: perfringo
  SyntaxError: unexpected character after line continuation character siteshkumar 2 288 Jul-13-2020, 07:05 PM
Last Post: snippsat
  Remove from end of string up to and including some character lbtdne 2 431 May-17-2020, 09:24 AM
Last Post: menator01
  create a list of object with a list of character studenthch 0 301 Feb-12-2020, 08:43 AM
Last Post: studenthch
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 535 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  Remove all \n from end of list items JackMack118 4 24,518 Dec-27-2019, 08:34 AM
Last Post: perfringo
  can't remove element from a list yokaso 6 592 Nov-06-2019, 03:11 PM
Last Post: yokaso
  with input remove a string from the list konsular 3 524 Oct-12-2019, 09:25 AM
Last Post: konsular
  weird result trying to remove numbers from a list Exsul 6 695 Aug-27-2019, 05:10 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020