0

It should be very easy, but I am looking for an efficient way to perform it.

I know that I could split the string into two parts and insert the new value, but I have tried to substitute each line between the indexes 22-26 as follows:

line.replace(line[22:26],new_value)

The Problem

However, that function substitutes everything in the line that is similar to the pattern in line[22:26].

In the example below, I want to replace the marked number 1 with number 17:

enter image description here

Here are the results. Note the replacement of 1 with 17 in several places:

enter image description here

Thus I don't understand the behavior of replace command. Is there a simple explanation of what I'm doing wrong?

Why I don't want RE

The values between index 22-26 are not unified in form.

Note: I am using python 3.5 on Unix/Linux machines.

1
  • line[22:26] gives you a string with 1 and some spaces. You use this pattern to replace every occurences in this line by new_value. Commented Feb 16, 2017 at 14:21

1 Answer 1

1

str.replace replaces 1 sub-string pattern with another everywhere in the 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')
# also produces output 'xy cd xy xy'

what you could do instead, to replace just the characters in position 22-26

line = line[0:22] + new_value + line[26:]

Also, looking at your data, it seems to me to be a fixed-width text file. While my suggestion will work, a more robust way to process this data would be to read it & separate the different fields in the record first, before processing the data.

If you have access to the pandas library, it provides a useful function just for reading fixed-width files

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.