Domanda

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']
È stato utile?

Soluzione

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

my_file2.readline().strip()

Altri suggerimenti

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.

for i in range(numStations):
     allStations.insert(j,my_file2.readline().rstrip())
for line in file:
    data = line[:-1].split("\t")

I use this all the time for tab delimited data.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top