Showing posts with label python code. Show all posts
Showing posts with label python code. Show all posts

Wednesday, 21 December 2022

Replace String in Python

 

At times we need to replace strings in a statement or in a file. We will see here how we can replace a string with another in python.


To Replace a string in python, we can user replace() method.

Example: 

        old_string = "This is the old string."

        new_string = old_string.replace("old", "new")

        print(new_string)



This can also be achieved by using the 're' module of python, which is used for advanced string and regex replacements.

Code: 
    
        import re

        old_string = "This is the old string."
        new_string = re.sub("old", "new", old_string)
        print(new_string)



        Output: This is the new string.