Home >Backend Development >Python Tutorial >How Can I Efficiently Capture Multiline Raw Input in Python?

How Can I Efficiently Capture Multiline Raw Input in Python?

DDD
DDDOriginal
2024-11-24 06:52:13929browse

How Can I Efficiently Capture Multiline Raw Input in Python?

Multiline Raw Input in Python

Python offers multiple options for capturing multiline raw input from users. Here are two efficient methods:

Input() with Sentinel Value

In Python 3, input() can be used with a sentinel value to terminate input when a specific string is encountered. Here's an example:

sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
    # Process each line here

Joint Iteration

To obtain each line as a string, concatenate the lines using a newline character as a separator:

multi_line_input = '\n'.join(iter(input, sentinel))

Iter(raw_input) in Python 2

For Python 2, use iter(raw_input) instead of iter(input) with the sentinel value method:

multi_line_input = '\n'.join(iter(raw_input, sentinel))

The above is the detailed content of How Can I Efficiently Capture Multiline Raw Input in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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