0

I'm learning python and was wondering if it's possible to write the below code differently, but have the same function. The purpose of this code is to split \n and remove spaces from the right:

contents = readlines()
stripped_contents = [(element.rstrip()) for element in contents]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • The code is fine (but you can get rid of the parentheses surrounding `element.rstrip()`), why would you need another method of writing? Other ways would not be as good as yours’ – Taku Sep 03 '17 at 08:46
  • 1
    Possible duplicate of [Getting rid of \n when using .readlines()](https://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines) – OneCricketeer Sep 03 '17 at 08:48

1 Answers1

0

You don't need to call readlines if you're going to iterate over the file(?). Also, use better names like "line" instead of "element".

stripped_lines = [line.rstrip() for line in file]

If you're going to use stripped_lines immediately as an iterable and only once, use a generator expression instead.

stripped_lines = (line.rstrip() for line in file)
Harvey
  • 5,703
  • 1
  • 32
  • 41