0

I am creating a list from a.txt where each element is a line in the txt file with the code:

var_names = []
with open('filevarname.txt', 'r') as f1:
    var_names = f1.readlines() 

and this does produce the list, however, each element ends with "\n" so the var_names list looks like

var_names = [ 'var_name1\n', 'var_name2\n', 'var_name3\n', 'var_name4\n']

I have tried to use

var_names = map(lambda s: s.strip(), var_names)

and

var_names = map(lambda line: line.rstrip('\n'), var_names)

but when I run those line of codes the lists disappear, it's like it is getting deleted.

I know I'm missing something obvious, but it's not obvious to me so any help would be much appreciated.

I'm using spyder on a mac if that makes a difference.

KevOMalley743
  • 551
  • 3
  • 20
  • `sle_r_name = [x.rstrip() for x in f1]` should do it - no need to `.readlines()` a text file is iterable linewise as is. – Patrick Artner Feb 28 '19 at 14:11
  • 1
    You need a `list()` wrap, if you're working on Python 3: `list(map(lambda s: s.strip(), var_names))`. Note, its not like list is getting deleted, but represented as a `map` object. – Austin Feb 28 '19 at 14:13
  • @Austin thanks a million, this worked as well as the answer posted below. Its good to know I can do it in a couple of different ways. – KevOMalley743 Feb 28 '19 at 14:17

1 Answers1

1

Use list comprehension:

var_names = [x.strip() for x in var_names]
Ohad Chaet
  • 489
  • 2
  • 12