Home >Backend Development >Python Tutorial >How Can I Read Input from Standard Input (stdin) in Python?
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.
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.
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!