This tutorial help to replace a character or substring using regex.Python’s re module help to regex with python.
Python Regex
A Regular Expression (RegEx) is a special sequence of characters that defines a search pattern. This helps you match or find other strings or sets of strings.
Python re Module
Python provides a built-in library called re
for working with Regular Expressions. Thanks to the Python module re, regular expressions are fully supported in Python. The re
module uses re.error
to handle errors that occur while compiling or using a regular expression.
Checkout other python String tutorials:
- How To Convert Python String To Array
- How to Trim Python string
- Python String join Example
- Python Array of Strings
- Python re match Example
Replace Using re.sub() Method
The re.sub() function is used to replace substrings in strings.
The Syntax:
result = re.sub(pattern, repl, string, count=0, flags=0);
This method returns a string where matched occurrences are replaced with the content of replace variable.
How To Replace & to dot(.)
Let’s create a python code to replace & with dot using re.sub method.
import re string = 'Hello! I am lin& I want to know about you\ & where you live & \n Your profession&' # matches pattern = r'&' replace = '.' new_string = re.sub(pattern, replace, string) print(new_string)
Output :
Hello! I am lin. I want to know about you. where you live . Your profession.
How To Replace White Space in a String
Let’s create a python code to replace & with dot using re.sub
method.
import re string = 'Hello! I am lin' # matches pattern = r'\s+' replace = '' new_string = re.sub(pattern, replace, string) print(new_string)
Output :
Hello!Iamlin