How can I use "number placeholders" when using .replace()?

Question:

I have a file which has multiple instances of "position": [num, num] (num is a random number).

Now I want to replace those instances with "position": [num, num, 0], so basically just add a , 0 after the two numbers. But how can I do that?

I tried doing text.replace('"position": [%d, %d]', '"position": [%d, %d, 0]'). That didn’t work though.

Asked By: LiQ

||

Answers:

You can use the following re.sub to do the replacements (demo).

Edit for OP’s comments:

Given that the file is fairly small, I’d iterate through it while reading, applying the substitution as I go, and then dump all the subbed lines into the same location.

import re

file_path = "/tmp/74987707.txt"  # substitute your own

output_lines = []

with open(file_path, mode="rt") as f:
    for line in f:
        subbed_line = re.sub(
            r'("position": [d+(?:.?d*), d+(?:.?d*))(])',
            r'1, 02',
            line
            )
        output_lines.append(subbed_line)

with open(file_path, mode="wt") as f:
    f.writelines(output_lines)

Regex explanation:

  1. group 1 ("position": [d+(?:.?d*), d+(?:.?d*))
  • ( start
  • "position": [ match exactly (escaping [)
  • d+ match one or more digit
  • (?:.?d*) non capturing group, match a possible literal dot . and one or more digits
  • , match exactly
  • d+(?:.?d*) see above
  • ) end
  1. group 2 (])
  • ( start
  • ] match exactly (escaping ])
  • ) end
Answered By: ljmc

From the structure of what you posted it looks like a json file, you can just loop through the items and append 0

import json

with open('example.json', 'r') as f:
    data = json.load(f)

for item in data:
    if 'position' in item:
        if isinstance(item['position'], list) and len(item['position']) == 2:
            item['position'].append(0)

with open('example_modified.json', 'w') as f:
    json.dump(data, f)
Answered By: Joe S
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.