I have a question with Stdin.readlines, I'm not sure how to use it; for example I have this paragraph
Adventures in Disneyland Two blondes were going to Disneyland when they came to a fork in the road. The sign reads: "Disneyland Left." So they went home.
But when I print it I get something like this:
['Adventures in DisneylandTwo blondes were going to Disneyland when they came to fork in the road. The sign read: "Disneyland Left." So they went home.\n', '\n']
My idea was that each word would be separated as an element, but here an element is a phrase, My input is Mensaje=stdin.readlines()
, but I don't know how to use this very well, I've tried to put a split()
or strip()
but this gives me an attribute error.
Can someone explain to me how it works stdin.readlines()
and what attributes it has?
Thank you!
The method
readlines()
(either onstdin
or on another file), what it returns is a list , whose elements are the read lines. It doesn't separate by phrases, as you said, but by carriage returns. Every time a carriage return appears in the input, that terminates a line and that line is added to the list that will eventually be returned.When you try to apply
split()
on what it returnsreadlines()
logically it gives you an error, because what it returns is a list that has no methodsplit()
.If what you want is to receive a list of words instead of lines, the easiest solution is to read the whole file with
read()
, and since in this case you will receive a string, apply the methodsplit()
on it, to split it into words. If yousplit()
don't pass parameters to it, it will use spaces or carriage returns interchangeably as word separators.Keep one thing in mind though. You are reading from standard input, so the above line will not return the list of words until the standard input has been "exhausted" (read completely). When you run the script redirecting input from a file, this will happen at the end of the file, which is what we want. But if you run it in interactive mode, the user will have to type all the lines, using carriage returns if they want to separate the lines, and finally pressing Ctrl+D to indicate the end of the input. As long as Ctrl+D is not pressed, the program will continue to wait for data from
stdin
.