简体   繁体   中英

Replace part of a matched string in python

I have the following matched strings:

punctacros="Tasla"_TONTA  
punctacros="Tasla"_SONTA  
punctacros="Tasla"_JONTA  
punctacros="Tasla"_BONTA

I want to replace only a part (before the underscore) of the matched strings, and the rest of it should remain the same in each original string.

The result should look like this:

TROGA_TONTA  
TROGA_SONTA  
TROGA_JONTA  
TROGA_BONTA
mystring.replace('punctacross="Tasla"', 'TROGA_')

where mystring is string with those four lines. It will return string with replaced values.

If you want to replace everything before the first underscore, try this:

#! /usr/bin/python3

data = ['punctacros="Tasla"_TONTA',
'punctacros="Tasla"_SONTA',  
'punctacros="Tasla"_JONTA',  
'punctacros="Tasla"_BONTA',
'somethingelse!="Tucku"_CONTA']

for s in data:
    print('TROGA' + s[s.find('_'):])

Edit:

This should work:

from re import sub
with open("/path/to/file") as myfile:
    lines = []
    for line in myfile:
        line = sub('punctacros="Tasla"(_.*)', r'TROGA\1', line)
        lines.append(line)
with open("/path/to/file", "w") as myfile:
    myfile.writelines(lines)

Result:

TROGA_TONTA  
TROGA_SONTA  
TROGA_JONTA  
TROGA_BONTA

Note however, if your file is exactly like the sample given, you can replace the re.sub line with this:

line = "TROGA_"+line.split("_", 1)[1]

eliminating the need of Regex altogether. I didn't do this though because you seem to want a Regex solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM