Reputation: 23
I have a problem why this code. Why does the string length not match with my input?
input: a
output: 2
from sys import stdin
for line in stdin:
print(len(line))
Upvotes: 2
Views: 1093
Reputation: 140168
like any file-like iterator, stdin
yields lines with linefeeds/newlines when iterated upon. Which explains you get an extra char when counting.
You could use rstrip("\n")
to make the count right (remove right hand newline):
from sys import stdin
for line in stdin:
print(len(line.rstrip("\n")))
(note that substracting 1 to the result also works)
Upvotes: 2
Reputation: 1017
I guess it also contains your linefeed character '\n'
try this code :
from sys import stdin
for line in stdin:
for x in line:
print(x)
Upvotes: 1