how to Continuous search and replace until the string not find in python?

Viewed 147

I want to remove all the empty elements in the below string. If parent element is containing only empty child elements, then we need to remove the parent elements as well.

Actually, I am providing the replace function in perl below. But, I need it in python.

Perl:


    while($text =~ s/<[^\/><]+>\s*<\/[^\/><]+>//si){}

**Here is my Input string:**
text = <transaction>
    <trans>content</trans>
    <dir></dir>
    <curr>
        <currency></currency>
        <amount></amount>
    </curr>
</transaction>

**Here is my Output string:**
text = <transaction>
    <trans>content</trans>
</transaction>
1 Answers

You can try to remove all tags that empty or tags that only contain whitespace characters by the re.findall method and when it will not find any tags the loop will end and print the new text variable.

import re

text = """<transaction>
    <trans>content</trans>
    <dir></dir>
    <curr>
        <currency></currency>
        <amount></amount>
    </curr>
</transaction>"""


empty_tags = True
while empty_tags:
    empty_tags = re.findall(r"\s*<.*></.*>|\s*<\w*>\W+</.*>", text)
    for tags in empty_tags:
        text = text.replace(tags, '')
print(text)

Output

<transaction>
    <trans>content</trans>
</transaction>
Related