Luchko Serega Luchko Serega - 1 year ago 73
Python Question

Python find strings and replace

I have string in Python :

s = "htmlhtl {% static path1 %} htmlhtml {% static path2/path3 %} htmlhtml "

and variable :

path = ""

I want to make from s new string which will contain on the places of the
{% static ... %}
tag paths to folders:

"htmlhtl htmlhtml htmlhtml"

I have opened python doc, and have tried to do it by myself but I can't even match tags. The task seems to be very often case for regexp.

Jan Jan
Answer Source

You can either use Django's builtin methods or a simple regex to achieve the same:

import re

s = "htmlhtl {% static path1 %} htmlhtml {% static path2/path3 %} htmlhtml " 

rx = re.compile(r'{% static (?P<path>\S+) %}')
# search for {% static ...%}

s = rx.sub(r'\g<path>', s)
# htmlhtl htmlhtml htmlhtml 

See a working demo on

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download