python 3.x - substitue string by index without using regular expressions -
it should easy, looking efficient way perform it.
i know split string 2 parts , insert new value, have tried substitute each line between indexes 22-26 follows:
line.replace(line[22:26],new_value)
the problem
however, function substitutes in line similar pattern in line[22:26]
.
in example below, want replace marked number 1 number 17:
here results. note replacement of 1
17
in several places:
thus don't understand behavior of replace
command. there simple explanation of i'm doing wrong?
why don't want re
the values between index 22-26 not unified in form.
note: using python 3.5 on unix/linux machines.
str.replace
replaces 1 sub-string pattern everywhere in string.
e.g.
'ab cd ab ab'.replace('ab', 'xy') # produces output 'xy cd xy xy'
similarly,
mystr = 'ab cd ab ab' mystr.replace(mystr[0:2], 'xy') # produces output 'xy cd xy xy'
what instead, replace just characters in position 22-26
line = line[0:22] + new_value + line[26:]
also, looking @ data, seems me fixed-width text file. while suggestion work, more robust way process data read & separate different fields in record first, before processing data.
if have access pandas library, provides useful function reading fixed-width files
Comments
Post a Comment