在 python 中打印每行标准输入的字符串长度
Print length of strings from each line of stdin in python
我想从 stdin 打印每个字符串的长度。没有给出字符串的数量。请提出一些方法。我正在尝试的是:
import sys
for line in sys.stdin:
s= str(line)
print len(s),
例如输入为:
ram
sita
geeta
所需的输出是 3 4 5
但它正在打印 4 5 5
因为
ram
sita
geeta
实际上是...
ram\n
sita\n
geeta
还有...
>>> len('\n')
1
>>> len('ram\n')
4
>>>
所以你需要...
import sys
for line in sys.stdin:
s = str(line.strip())
print len(s),
演示:
[user@localhost ~]$ python2 test.py
ram
sita
geeta
3 4 5
[user@localhost ~]$
关于str.strip()
:
strip(...)
S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None
, remove characters in chars instead.
您可以 str.rstrip
在输入上删除任何换行符,并使用 end=" "
和 print 在同一行上获得由 space
分隔的输出
from __future__ import print_function
import sys
print(*(len(line.rstrip()) for line in sys.stdin),end= " ")
我想从 stdin 打印每个字符串的长度。没有给出字符串的数量。请提出一些方法。我正在尝试的是:
import sys
for line in sys.stdin:
s= str(line)
print len(s),
例如输入为:
ram
sita
geeta
所需的输出是 3 4 5
但它正在打印 4 5 5
因为
ram
sita
geeta
实际上是...
ram\n
sita\n
geeta
还有...
>>> len('\n')
1
>>> len('ram\n')
4
>>>
所以你需要...
import sys
for line in sys.stdin:
s = str(line.strip())
print len(s),
演示:
[user@localhost ~]$ python2 test.py
ram
sita
geeta
3 4 5
[user@localhost ~]$
关于str.strip()
:
strip(...)
S.strip([chars]) -> str
Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not
None
, remove characters in chars instead.
您可以 str.rstrip
在输入上删除任何换行符,并使用 end=" "
和 print 在同一行上获得由 space
from __future__ import print_function
import sys
print(*(len(line.rstrip()) for line in sys.stdin),end= " ")