How to Replace String in Python | Python String Replacement with regular expression

Last updated Mar 11, 2021

String is a sequence of characters, Strings are the important topic in every programming language. Strings has different properties with respect to programming method. In this post we will cover String replacement in python.

String can be replace with other strings. To replace a string in python by replace() function. To replace a string of specific pattern then we will use regular expression.

Replace a string with regular expression it will search the pattern and replace that with current string. In python to use regular expression we will use re module. One thing we need to observe is string replacement with regular expression is slow compare with general replace() function. We will use string replacement with regular expression when we want to replace a complicated string patterns.

 

re module example

To work with regular expressions we need to import re module in the code

The sub() function will be used to replaces the string

import re

#Replaces all ' ' characters with the digit "_":

txt = "The python replace regular expression"
x = re.sub("\s", "_", txt)
print(x)

 

 

 

Here are the some regular expression characteristics

Character Description Example
[] A set of characters "[a-m]"
\ Signals a special sequence "\d"
. Any character (except newline character) "he..o"
^ Starts with "^hello"
$ Ends with "world$"
* Zero or more occurrences "aix*"
+ One or more occurrences "aix+"
{} Exactly the specified number of occurrences "al{2}"
| Either or "falls|stays"

 

 

Python String replace regular expression examples

 

1) Replace String with Exact match by regular expression


# Import regex module
import re

# Define a string
orgStr = "A Beautifull flower blossom"

# Replace the string
repStr = re.sub("flower", "rose", orgStr)

# Original string
print("Original Text:", orgStr)

# Replaced string
print("Replaced Text:", repStr)

 

Output

Original Text: A beautiful flower blossom
Replaced Text: A beautiful rose blossom

 

 

2) Replace String at start position

# Import regex module
import re

# Read a string input
originalText = input("Enter a text\n")

# Replaces the String based on the pattern
replacedText = re.sub('^[A-Za-z]+' , 'welcome', originalText)

# Replaced string
print("Replaced Text:", replacedText)

 

In the above example we have used '^[A-Za-z]+' regular pattern to check the alphabets

Then it will replace the start string with welcome

 

Output

Enter a text
string uppercase 124 change
Replaced Text:  hello uppercase 124 change

 

 

3) Search and Replace string at the end

To replace the string at end position by using '[a-z0-9]+$'. This pattern will search all small letters and numbers at end of the string and return true if the matched string find in the string.

 

# Import regex module
import re


originalText = input("Enter a email address\n")


replacedText = re.sub('[a-z0-9]+$' , 'in.com', originalText)


print("Replaced Text:", replacedText)

 

Output

Enter a email address
example@gmail.com
Replaced Text: example@gmail.in.com

 

 

4) Replace the specific part of a string

To replace a string pattern wich matches at the specific position we will use '#[a-z]*'. This will search the any sub string starts with alphabets followed by '#' symbol

# Import regex module
import re


coupon = 'My Coupon #python coupon'


replacedText = re.sub('#[a-z]*', '#COUPON123', coupon)


print("Original Text:", coupon)


print("\nReplaced Text:", replacedText)

 

Output

Original Text: My Coupon #python coupon

Replaced Text: My Coupon #COUPON123 coupon
>

 

Conclusion: By using a reugular expression we can replace any string in pythion with pattern search based.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

885 Views