Luchko Serega Luchko Serega - 1 month ago 11
Python Question

Python find strings and replace

I have string in Python :

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


and variable :

path = "www.static.com"


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

"htmlhtl www.static.com/path1 htmlhtml www.static.com/path2/path3 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

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'www.static.com/\g<path>', s)
print(s)
# htmlhtl www.static.com/path1 htmlhtml www.static.com/path2/path3 htmlhtml 


See a working demo on ideone.com.