Jython: How to remove '\n' from the end of a string being read in [duplicate]

StackOverflow https://stackoverflow.com/questions/8449796

  •  12-03-2021
  •  | 
  •  

سؤال

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']
هل كانت مفيدة؟

المحلول

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

my_file2.readline().strip()

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top