Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace the content in between angle brackets (<>)

Tags:

python

regex

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?

like image 544
ahri Avatar asked Oct 13 '14 02:10

ahri


People also ask

How do you replace brackets in Python?

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.

How do I extract text between brackets in Python?

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.

WHAT IS RE sub in Python?

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.


1 Answers

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.

like image 153
ilent2 Avatar answered Nov 14 '22 23:11

ilent2