How to Accept Multiline Input in Python?
When developing Python programs, you may encounter scenarios where you need to gather several lines of user input. This input can consist of sentences or specific data points, each occupying its own line.
Method:
One effective way to handle multiline input is through the use of an infinite iterator, iter(), in combination with a sentinel variable. A sentinel variable signifies the end of the input.
In Python 3 and above:
sentinel = '' # ends when this string is seen for line in iter(input, sentinel): pass # do things here
Explanation:
Example:
Consider the following user input:
This is a multilined input. It has multiple sentences. Each sentence is on a newline.
The code above would read each line into the line variable and allow further processing to be performed.
To obtain the entire multiline input as a single string, use:
'\n'.join(iter(input, sentinel))
The above is the detailed content of How Can I Get Multiline User Input in Python?. For more information, please follow other related articles on the PHP Chinese website!