user3123767
user3123767

Reputation: 1165

Python code for replacing texts not working

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.

Upvotes: 2

Views: 149

Answers (1)

falsetru
falsetru

Reputation: 369054

\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)

Upvotes: 2

Related Questions