Tedee12345
Tedee12345

Reputation: 1210

Python how to improve this example?

I have a file:

one two three
four five six

I tried this command:

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

I want to get the result:

one xxx three
four five six

How to improve the above example?

Upvotes: 0

Views: 73

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 113905

You didn't properly escape the double quotes

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

Upvotes: 1

Azwr
Azwr

Reputation: 784

You have to backshlash(escape) the two and xxxor single-quote it. This will work

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

Upvotes: 2

Related Questions