Home > Backend Development > Python Tutorial > How Can I Get Multiline Input in Python?

How Can I Get Multiline Input in Python?

Patricia Arquette
Release: 2024-11-09 16:51:02
Original
239 people have browsed it

How Can I Get Multiline Input in Python?

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)
Copy after login

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
'''
Copy after login

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
    ''')
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template