5

From a text file lines_of_words.txt, say

first
second
third

a list of words as strings has to be created, i.e.

list_of_strings = ['first', 'second', 'third']

This seems like an extremely trivial function, but I can't find a concise solution. My attempts are either too cumbersome or produce a wrong output, e.g.

['f', 'i', 'r', 's', 't', '\n', 's', 'e', 'c', 'o', 'n', 'd', '\n', 't', 'h', 'i', 'r', 'd', '\n']

or

first
second
third

What is the most pythonic function to get this done? My starting point so far has been

with open('list_of_words', 'r') as list_of_words:
    # Do something...
print(list_of_strings)
leonheess
  • 16,068
  • 14
  • 77
  • 112

2 Answers2

4

You just can use list(..) here on the file handler. Since the strings will contain a new line, you might want to use str.rstrip to remove the '\n' part at the right:

with open('list_of_words', 'r') as f:
    list_of_strings = list(map(str.rstrip, f))
print(list_of_strings)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thanks, this is perfect. –  Jul 21 '19 at 19:03
  • One question: Where does `str` in `str.rstrip` point to, i.e. how does the interpreter know that `str` refers to the individual strings inside `list_of_strings`? This works fine (while e.g. `map(rstrip(), f)` does not), it's just that `str` seems to fall out of the blue. –  Jul 21 '19 at 19:25
  • @david: `str` referis to the `str` class. If a method it defined on the class level (and it is not a static method or class method), then `str.foo(x)` is the same as `x.foo()` given `x` is a string. – Willem Van Onsem Jul 21 '19 at 19:26
  • Is there a technical name for this behaviour? –  Jul 22 '19 at 14:52
  • @david: in mathematics, that would be "partial application". The behavior s explained here https://stackoverflow.com/q/2709821/67579 for example. – Willem Van Onsem Jul 22 '19 at 15:00
3
with open('list_of_words', 'r') as f_in:
    data = [*map(str.strip, f_in)]

print(data)

Prints:

['first', 'second', 'third']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91