1

I have query.I am new to Python

Lets say I have a file in.txt. Inside this file I have some name like below.

Sunday

Monday

Tuesday
.
.

I want to put them into a list, I am doing:

#!/usr/bin/python3
with open("in.txt") as f:
lines = f.readlines()
lines = [l for l in lines]
print (lines);

The output is:

['Sunday\n', 'Monday\n', 'Tuesday\n']

I want to print it like:

['Sunday', 'Monday', 'Tuesday']

how will I remove \n

Any suggestion will great help, I tried rstrip() it didn't work.

s.k.Dash
  • 57
  • 4

3 Answers3

1

Try this :

lines = [l.strip() for l in lines]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

It should work with rstrip() or even strip(), like this:

with open("in.txt") as f:
    lines = f.readlines()

lines = [l.rstrip() for l in lines]
print (lines)

Or, more concisely:

with open("in.txt") as f: 
    lines = [line.rstrip() for line in f]
Guybrush
  • 2,680
  • 1
  • 10
  • 17
1

Use a list comprehension with rstrip:

with open("in.txt") as f:
    lines = [i.rstrip() for i in f]
print(lines)

Output:

['Sunday', 'Monday', 'Tuesday']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114