Python equivalent of C++ getline()
In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in开发者_StackOverflow Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize this so that I can specify my own delimiter?
Do you still want to press enter to create multiple lines? How do you end the input? Or do you want do specify multiple lines on a single line?
If the former, try looping raw_input() until something is written that tells it to stop:
lines = []
while True:
user_input = raw_input()
if user_input.strip() == "": # empty line signals stop
break
lines.append(user_input)
Or to specify multiple lines on a single line using a delimiter:
lines = raw_input().split(";")
You can try modify this method a bit to use it and use it in your program.
First, import the linecache module:
import linecache
The linecache module allows you to access any line from any file. Of its three methods, the one you are likely to use the most is getline. The syntax for getline is as follows:
linecache.getline('filename', line_number)
If you have a file called 'myfile.txt' and would like to read line 138 from it, getline allows you to do so with ease.
retrieved_line = linecache.getline('myfile.txt', 138)
Then you can simply print retrieved_line or otherwise manipulate the data of line 138 without doing surgery on the file itself.
You will need to implement such a function yourself. For example:
def getline(stream, delimiter="\n"):
def _gen():
while 1:
line = stream.readline()
if delimiter in line:
yield line[0:line.index(delimiter)]
break
else:
yield line
return "".join(_gen())
import sys
getline(sys.stdin, ".")
精彩评论