Multiline Input Handling in Python
While Python 3 introduced the input function as a replacement for raw_input, the former lacks the ability to accept multiline input. This limitation can be overcome through various approaches.
Utilizing a Loop
One solution is to employ a loop that continues until an End-of-File (EOF) character is encountered. This technique enables the program to read input line by line and store it in a list or variable.
# Python 3 print("Enter/Paste your content. Ctrl-D or Ctrl-Z (Windows) to save it.") contents = [] while True: try: line = input() except EOFError: break contents.append(line) # Python 2 print "Enter/Paste your content. Ctrl-D or Ctrl-Z (Windows) to save it." contents = [] while True: try: line = raw_input("") except EOFError: break contents.append(line)
Using Multi-Line String Literals
Another approach is to utilize multi-line string literals enclosed in triple quotes. These literals can be assigned to a variable and treated like a multiline input.
multi_line_input = ''' Line 1 Line 2 Line 3 '''
Third-Party Modules
Alternatively, third-party modules such as textwrap can be employed to facilitate multiline input handling.
import textwrap multi_line_input = textwrap.dedent(''' Line 1 Line 2 Line 3 ''')
The above is the detailed content of How Can I Get Multiline Input in Python?. For more information, please follow other related articles on the PHP Chinese website!