Home > Back-end >  Python regex sub nth item in comma separated string [duplicate]
Python regex sub nth item in comma separated string [duplicate]

Time:10-01

How can I re.sub the nth item of a string of a comma separated list?

My list looks like this:

"Breach Geom=80,80,31,0,0,False,0.5,34.8,14,2.6"

I want to change the value of the nth item in the list, for example changing the third item 31 to 35 would look like:

"Breach Geom=80,80,35,0,0,False,0.5,34.8,14,2.6"

I have tried things like

[\d]*(?=,{n})
[\d]*(?=[,\d]{n})

CodePudding user response:

Try this :

import re

def sub_nth(text, i, value):
    def repl(matchobj):
        lst = matchobj.group().split(',')
        lst[i] = str(value)
        return ','.join(lst)

    return re.sub(r'(?<==). $', repl, text)


s = "Breach Geom=80,80,31,0,0,False,0.5,34.8,14,2.6"
print(sub_nth(s, 2, 35))

output:

Breach Geom=80,80,35,0,0,False,0.5,34.8,14,2.6

explanation :

sub_nth function gets a text, index, and new value. (?<==). $ pattern will match everything after '='. Then I wrote a repl function which will be called whenever a match is found. I splited that matched string in order to make changes to the list then I joined it again.

CodePudding user response:

You can use the following regex and pass a function to change the value (here adding 4)

import re

s = "Breach Geom=80,80,31,0,0,False,0.5,34.8,14,2.6"

re.sub(r'^(\D (?:\d ,){2})(\d )',
       lambda x: x.group(1) str(int(x.group(2)) 4),
       s)

Output:

'Breach Geom=80,80,35,0,0,False,0.5,34.8,14,2.6'
  • Related