Python: Replace/remove string between two delimiters/characters

This Python code helps you to

  • to replace a string between two delimiters or characters
  • delete/remove string between two characters or delimiters

Python code to replace string between two delimiters

# This macro replaces nivas in below string with silveri
string = "sri[nivas]"
firstDelPos=string.find("[") # get the position of [
secondDelPos=string.find("]") # get the position of ]
stringAfterReplace = string.replace(string[firstDelPos+1:secondDelPos], "silveri") # replace the string between two delimiters
print stringAfterReplace # print the string after sub string between dels is replaced

Python code to delete/remove string between two characters/delimiters

Replace 5th line of above code with below one

stringAfterReplace = string.replace(string[firstDelPos+1:secondDelPos], "") # remove the string between two delimiters

Note: This code works in both Python 2 and 3

Read below post if you want to get/find sub string between two delimiters/characters within a string

About the Author


A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published. Required fields are marked *