Bottom Page

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!
Quote
#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]
Quote
#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!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Remove from end of string up to and including some character lbtdne 2 222 May-17-2020, 09:24 AM
Last Post: menator01
  create a list of object with a list of character studenthch 0 152 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 280 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  Remove all \n from end of list items JackMack118 4 12,004 Dec-27-2019, 08:34 AM
Last Post: perfringo
  can't remove element from a list yokaso 6 327 Nov-06-2019, 03:11 PM
Last Post: yokaso
  with input remove a string from the list konsular 3 338 Oct-12-2019, 09:25 AM
Last Post: konsular
  weird result trying to remove numbers from a list Exsul 6 480 Aug-27-2019, 05:10 AM
Last Post: perfringo
  How to remove multiples in a list jasper100125 6 533 Aug-20-2019, 06:38 AM
Last Post: buran
  Remove \n from list of values within a pandas columns klllmmm 2 2,048 Jun-24-2019, 05:16 AM
Last Post: klllmmm
  remove string character from url jacklee26 10 1,492 Mar-25-2019, 03:56 PM
Last Post: Larz60+

Forum Jump:


Users browsing this thread: 1 Guest(s)