Home >Backend Development >Python Tutorial >How to Read Multiple Lines of User Input in Python?

How to Read Multiple Lines of User Input in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 04:42:18741browse

How to Read Multiple Lines of User Input in Python?

Reading Multiple Lines of Raw Input in Python

To read multiple lines of user input, utilize the iter(input, sentinel) function. It continuously reads and yields lines until the sentinel string is encountered, serving as the loop's termination condition. For instance:

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

To obtain each line as a string, employ:

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

In Python 2, use:

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

This approach continuously reads lines from the user and continues until the sentinel string is entered. Each line can then be individually processed or joined together to form a multiline input string.

The above is the detailed content of How to Read Multiple Lines of User 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