Home >Backend Development >Python Tutorial >How Can I Read Input from Standard Input (stdin) in Python?

How Can I Read Input from Standard Input (stdin) in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 06:57:21362browse

How Can I Read Input from Standard Input (stdin) in Python?

Reading Input from Standard Input (stdin)

In code golfing challenges, participants often encounter a requirement to read input from standard input (stdin). To accomplish this task, Python provides a straightforward method using the fileinput module.

Using fileinput

To read line by line from stdin using the fileinput module, employ the following code:

import fileinput

for line in fileinput.input():
    pass

This code initializes the fileinput module and instructs it to read input from stdin. The module then returns an iterator that allows you to iterate over each line of input.

Note

It's important to note that the retrieved line contains a trailing newline character. If desired, you can remove it using the rstrip() method:

line = line.rstrip()

The above is the detailed content of How Can I Read Input from Standard Input (stdin) 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