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
Release: 2024-12-03 04:42:18
Original
800 people have browsed it

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

To obtain each line as a string, employ:

'\n'.join(iter(input, sentinel))
Copy after login

In Python 2, use:

'\n'.join(iter(raw_input, sentinel))
Copy after login

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!

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