【问题标题】:Spacing in program using stdout使用标准输出的程序间距
【发布时间】:2017-02-09 12:41:48
【问题描述】:

我有两个文件,'something.txt' 'program.py'

这是我的程序:

#!/usr/bin/python

## your code here
import sys

line = ""
for n in [line for line in sys.stdin.readlines()]:
    sys.stdout.write(n.split()[0]+n.split()[9]+'\n') 

运行时

$ more something.txt | python program.py

我明白了

199.72.81.556245
unicomp6.unicomp.net3985
199.120.110.214085
burger.letters.com0
199.120.110.214179
burger.letters.com0
burger.letters.com0
163.205.53.1455666
163.205.53.1428219
163.205.53.141204
tiger2.ocs.lsu.edu8677
199.0.2.275866
tornado.umd.edu5494

我想在 'n.split()[0]' 和 'n.split()[9]' 之间留一个空格

199.72.81.55 6245
unicomp6.unicomp.net 3985
199.120.110.21 4085
burger.letters.com 0
199.120.110.21 4179
burger.letters.com 0
burger.letters.com 0
163.205.53.145 5666
163.205.53.142 8219
163.205.53.14 1204
tiger2.ocs.lsu.edu 8677
199.0.2.27 5866
tornado.umd.edu 5494

但是

sys.stdout.write(n.split()[0]+' 'n.split()[9]+'\n')

sys.stdout.write(n.split()[0]+" "n.split()[9]+'\n')

无效。 有人可以帮忙吗?

【问题讨论】:

  • sys.stdout.write(n.split()[0]+' '+n.split()[9]+'\n')
  • @Rahul K P facepalm 谢谢
  • useless use of more 是反模式之上的反模式。 python whatever <file 是将 file 传递给 Python 脚本作为几乎每个 shell 中的标准输入的正确方法。
  • @tripleee 是的,我很清楚这一点,但是教练希望我们练习使用管道 |
  • 即便如此,像 more 这样的交互式程序相对于更传统的无用 cat 的价值是负面的 - 更复杂和更昂贵,没有实际好处,因为你没有而且确实不能使用它功能。

标签: python stdout spacing


【解决方案1】:

你快到了,用这个,

sys.stdout.write(n.split()[0]+' '+n.split()[9]+'\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多