Search code examples
pythonpython-3.xlistreplacereadlines

How to replace() a specific value within a list item directly after a keyword


Currently have a standard txt-style file that I'm trying to open, copy, and change a specific value within. However, a standard replace() fn isn't producing any difference. Here's what the 14th line of the file looks like:

 '    Bursts: 1 BF: 50 OF: 1  On: 2 Off: 8'

Here's the current code I have:

conf_file = 'configs/m-b1-of1.conf'
read_conf = open(conf_file, 'r')
conf_txt = read_conf.readlines()

conf_txt[14].replace(conf_txt[14][13], '6')

v_conf

Afterwards, though, no changes have been applied to the specific value I'm referencing (in this case, the first '1' in the 14th line above.

Any help would be appreciated - thanks!


Solution

  • There are few things here I think:

    1. I copied your string and the first 1 is actually character 12
    2. replace result needs to be assigned back to something (it gives you a new string)
    3. replace, will replace all "1"s with "6"s!

    Example:

    >>> a = '    Bursts: 1 BF: 50 OF: 1  On: 2 Off: 8'
    >>> a = a.replace(a[12], '6')
    >>> a
    '    Bursts: 6 BF: 50 OF: 6  On: 2 Off: 8'
    

    If you only want to replace the first instance (or N instances) of that character you need to let replace() know:

    >>> a = '    Bursts: 1 BF: 50 OF: 1  On: 2 Off: 8'
    >>> a = a.replace(a[12], '6', 1)
    >>> a
    '    Bursts: 6 BF: 50 OF: 1  On: 2 Off: 8'
    

    Note that above only "Bursts" are replaced and not "OF"