swapping position of two specific numbers in a text file python?

Question:

I want to swap two numbers position on each line of the text file after i replace equal symbol with this ‘|’ and save it, but I’m having trouble to do that! For instance

123456789=123456789

i wanted it to look like this:

123453489=126756789

As you can see, I swapped 34 with 67!

This is my code:

with open('track.txt', 'r') as z:
 data = z.read()
 
data = data.replace('=', '|')
  
with open('track2.txt', 'w') as z:
  z.write(data)

Thank you very much!
Sorry for my English.

Asked By: Zakaria Halloumi

||

Answers:

Use a regular expression with capture groups, so you can copy to the replacement in a different order.

import re

with open('track.txt', 'r') as z:
    data = z.read()
 
data = re.sub(r'^(.{5})(.{2})(.*)=(.{2})(.{2})(.*)$', r'153|426', data, flags=re.MULTILINE)

with open('track2.txt', 'w') as z:
    z.write(data)

The re.MULTILINE flag makes ^ and $ match the beginning and end of each line.

If you don’t like regular expressions, you can do it with slicing and concatenation in a loop.

new_data = ''

for line in data.splitlines():
    fields = line[:5], line[5:7], line[7:10], line[11:13], line[13:15], line[15:]
    new_data += fields[0] + fields[4] + fields[2] + '|' + fields[3] + fields[1] + fields[5]
Answered By: Barmar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.