-2

Possible Duplicate:
Python: How to remove /n from a list element?

I'm trying to read in data from text file but when the data is read in and added to an array, so is the '\n' because each set of data is on a new line.

  for j in range(numStations):
    allStations.insert(j, my_file2.readline())

Which results in an output of:

  ['H1\n', 'H2\n', 'H3\n', 'H4\n', 'H5\n', 'Harriston\n']
Community
  • 1
  • 1
Glynbeard
  • 1,389
  • 2
  • 19
  • 31

4 Answers4

1

If you want to get crazy with Python syntax:

map(lambda x: x.rstrip('\n'), input_list)

This is equivalent to:

[x.rstrip('\n') for x in input_list]

I'm not sure which one is faster, though. I just wanted to use a lambda.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • You could strip the line while it is being looped over like so: `foo.readline().rstrip('\n')` too. – Blender Dec 09 '11 at 18:12
1

Did you try the normal way of getting rid of whitespace?

my_file2.readline().strip()
Dave
  • 3,834
  • 2
  • 29
  • 44
0
for i in range(numStations):
     allStations.insert(j,my_file2.readline().rstrip())
Wissam Youssef
  • 800
  • 1
  • 10
  • 20
0
for line in file:
    data = line[:-1].split("\t")

I use this all the time for tab delimited data.

WombatPM
  • 2,561
  • 2
  • 22
  • 22