From a text file
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']
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)
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)
str.rstrippoint to, i.e. how does the interpreter know that
strrefers to the individual strings inside
list_of_strings? This works fine (while e.g.
map(rstrip(), f)does not), it's just that
strseems to fall out of the blue. — Jul 21, 2019 at 19:25
strreferis to the
strclass. 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
xis a string. — Jul 21, 2019 at 19:26