2

My code is this.

import fileinput
for line in fileinput.FileInput("aaaa.txt",inplace=1):
     map_dict = {'\N':'999999999', '[':'(', '&':'&'}
     line = ''.join(map_dict.get(c,c) for c in line)
     print line,

I experimented this with aaaa.txt but it's simply not replacing anything.

A simpler code that I know works is

import fileinput
for line in fileinput.FileInput("aaaa.txt",inplace=1):
    line = line.replace("\N","999999999")
    print line,

But I want to make the first code work, because it replaces multiple things.

user3123767
  • 1,115
  • 3
  • 13
  • 22
  • refer to this http://stackoverflow.com/questions/2484156/is-str-replace-replace-ad-nauseam-a-standard-idiom-in-python – shifu Jun 25 '14 at 15:34

1 Answers1

2

\N is two character string. (same as '\\N')

>>> '\N'
'\\N'
>>> len('\N')
2

But iterating a string yields single character strings.

>>> for ch in 'ab\Ncd':
...     print ch
...
a
b
\
N
c
d

The code never replace \ followed by N.

How about call replace multiple times?

for old, new in map_dict.iteritems():
    line = line.replace(old, new)
falsetru
  • 357,413
  • 63
  • 732
  • 636