How to Replace String in Python | Python String Replacement with regular expression
Last updated Mar 11, 2021String 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"
|
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
|
Output
Original Text: A beautiful flower blossom
Replaced Text: A beautiful rose blossom
|
2) Replace String at start position
# Import regex module |
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 |
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 |
Output
Enter a email address |
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 |
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 :
|
|
|
|
1123 Views |