简体   繁体   中英

Extracting String between two special characters and replacing it with new string in python

I am trying to extract a string between two characters and replace it with a new string in every occurance of old string in a file.

Example:

Str1= "portid.router.address_location"

str2= "$addressmap= portid.ipaddress"

Str1 and Str2 are part of single file. Also, str1 and str2 has numerous occurrences in my text file and I need to replace each occurrence of "portid" string with a string called "devicenumber'.

Correction to my question: portid variable is not stable one. port id variable will be keep changing for each file. Example: "portid_id6_add7" in one file and "portid_id100_add7"

If you want to use the regex module in python specifically then try something like to replace the occurence of a particular string with something else:

import re

lst = ['portid.router.address_location', '$addressmap= portid.ipaddress']
regex = re.compile('portid')

for string in lst:
   regex.sub('devicenumber', string)

Put this into your python shell and you will see every modified string.

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