Replace a part of a String with a certain pattern to another string

Question:

I’m using the Python code to try to modify a certain pattern in a string:

input_name = 'FILE_TO_MODIFY.txt'
output_name = 'FILE_TO_MODIFY_OUT.txt'

with open('D:/Users/Drive/SOLVER/PythonDataProcessing/UBX_messages/' + input_name, 'r') as f:
    data = f.read()
f.close()

print(len(data))

for i in range(len(data)):
    if data[i] == ' ' and data[i+1] == '=':
        data[i:i+13].replace(' ', ';')

print(data)

Basicaly I have the a large string like this:

    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_SPI = 0x20910353;         //Output rate of the UBX-MON-COMMS message on port SPI"
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART1 = 0x20910350;       //Output rate of the UBX-MON-COMMS message on port UART1"
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART2 = 0x20910351;   //Output rate of the UBX-MON-COMMS message on port UART2"

And I want to remove all the values after the equal character like this:

    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_SPI;          //Output rate of the UBX-MON-COMMS message on port SPI"
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART1;        //Output rate of the UBX-MON-COMMS message on port UART1"
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART2;    //Output rate of the UBX-MON-COMMS message on port UART2"

I just have to identify the start char ‘space’ following by ‘=’ and the stop char ‘;’ and to replace all inside this interval with a simple ‘;’. There are like around 700 lines, so it’s easier do it with Python! I’m open the code with a txt file and storing all in a string. I’ve been trying to use replace() but it’s doesn’t work.
OBS: All the values have the same size (32 bit hex value)

Asked By: Lincoln

||

Answers:

You can use a regular expression to do precisely that:

import re

text = [
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_SPI = 0x20910353; //Output rate of the UBX-MON-COMMS message on port SPI",
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART1 = 0x20910350; //Output rate of the UBX-MON-COMMS message on port UART1",
    "extern const uint32_t UBLOX_CFG_MSGOUT_UBX_MON_COMMS_UART2 = 0x20910351; //Output rate of the UBX-MON-COMMS message on port UART2",
]

exp_re = re.compile(r" = 0x[0-9]{8}")

clean_text = []
for line in text:
    clean_line = exp_re.sub("", line)
    clean_text.append(clean_line)
    print(clean_line)
Answered By: Pietro
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.