I want to replace the content in between <>
Ex:
Input:
this is a < test >
Output:
this is a < hh >
So far I have:
test = "this is a <test>"
test = re.sub(r"\<[^>]*\>", "hh", test)
print(test)
This will always erase the <>
and result an output like:
this is a hh
But what I want is:
this is a < hh >
How should I fix it?
Using the replace() Function to Remove Parentheses from String in Python. In Python, we use the replace() function to replace some portion of a string with another string. We can use this function to remove parentheses from string in Python by replacing their occurrences with an empty character.
Extract Text Between Parenthesis To extract the text between any characters, use a formula with the MID and FIND functions. The FIND Function locates the parenthesis and the MID Function returns the characters in between them.
sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string. To use this function, we need to import the re module first. import re.
As thefourtheye suggests, one solution is to do
newstr = 'hh'
test = re.sub(r'\<[^>]*\>', '<' + newstr + '>', test)
But I suspect a more optimal solution with re
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With