Reputation:
I have this code (test.py
) below:
import sys
for str in sys.stdin.readline():
print ('Got here')
print(str)
For some reason when I run the program python test.py
and then I type in abc
into my terminal I get this output:
>>abc
THIS IS THE OUTPUT:
Got here
a
Got here
b
Got here
c
Got here
It prints out Got here
five times and it also prints out each character a
, b
, c
individually rather than one string like abc
. I am doing sys.stdin.readline()
to get the entire line but that doesn't seem to work either. Does anyone know what I am doing wrong?
I am new to python and couldn't find this anywhere else on stackoverflow so sorry if this is a obvious question.
Upvotes: 0
Views: 1099
Reputation: 375494
readline() reads a single line. Then you iterate over it. Iterating a string gives you the characters, so you are running your loop once for each character in the first line of input.
Use .readlines(), or better, just iterate over the file:
for line in sys.stdin:
But the best way to get interactive input from stdin is to use input()
(or raw_input()
in Python 2).
Upvotes: 2
Reputation: 1008
You are looping through each character in the string that you got inputted.
import sys
s = sys.stdin.readline()
print ('Got here')
print(s)
# Now I can use string `s` for whatever I want
print(s + "!")
In your original code you got a string from stdin
and then you looped through ever character in that input string and printed it out (along with "Got here").
EDIT:
import sys
while True:
s = sys.stdin.readline()
# Now I can do whatever I want with string `s`
print(s + "!")
Upvotes: 1