Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: replacement replace wrong place of the line

I have original line:
2.48724e-008 0.00022974 0.65 1 4 0 0 0.0002 2 2 2 0
I want new line:
6.1054382342e-10 1.26357e-05 0.65 1 4 0 0 1.1e-05 2 2 2 0

Code:

replacement = {'2.48724e-008':'6.1054382342e-10','0.00022974':'1.26357e-05','0.0002':'1.1e-05')}
for src, target in replacement.iteritems():
      line = line.replace(src,target)

But result was:
6.1054382342e-10 1.1e-052974 0.65 1 4 0 0 1.1e-05 2 2 2 0

The second number is wrong. Seems like python found the '0.0002' in the original line and replace it with '1.1e-05' no matter what is after it.

Would you please help me with this?

like image 379
Guiyuan Avatar asked Dec 25 '22 08:12

Guiyuan


1 Answers

The problem comes from the fact that with a dict, the keys can appear in any order. An iterable (tuple or list) would suffice for what you do

replacement = (
  ('2.48724e-008','6.1054382342e-10'),
  ('0.00022974','1.26357e-05'),
  ('0.0002','1.1e-05')
)   
for src, target in replacement:
  line = line.replace(src,target)
like image 170
Sci Prog Avatar answered Jan 08 '23 18:01

Sci Prog