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 ''')
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3