Reputation: 3356
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.
Upvotes: 1
Views: 65
Reputation: 139
Here is an example solution I came up with to your provided information using regular expressions:
>>> import re
>>> s = "htmlhtl {% static path1 %} htmlhtml {% static path2/path3 %} htmlhtml "
>>> path = "www.static.com"
>>> pat = re.compile(r'\{%\s*static\s+([\w/]+)\s*%\}')
>>> re.sub(pat, path+r'/\1',s)
'htmlhtl www.static.com/path1 htmlhtml www.static.com/path2/path3 htmlhtml '
Upvotes: 0
Reputation: 43169
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
Upvotes: 1