Python如何改进这个例子?

时间:2014-01-28 17:03:16

标签: python

我有一个文件:

one two three
four five six

我试过这个命令:

python -c "import sys; print ''.join(x.replace("two", "xxx") for x in sys.stdin)"  < file

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <genexpr>
NameError: global name 'two' is not defined

我想得到结果:

one xxx three
four five six

如何改进上述例子?

2 个答案:

答案 0 :(得分:2)

您必须反斜杠(转义)twoxxx或单引号。 这将有效

python -c "import sys; print ''.join(x.replace(\"two\", \"xxx\") for x in sys.stdin)" < file

答案 1 :(得分:1)

你没有正确地逃避双引号

python -c 'import sys; print "".join(x.replace("two", "xxx") for x in sys.stdin)'  < filename