2016-10-26 119 views
1

我有串在Python:Python中找到字符串和替換

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

和變量:

path = "www.static.com"

我想從小號新的字符串,使該將包含在的地方條標籤路徑文件夾:

"htmlhtl www.static.com/path1 htmlhtml www.static.com/path2/path3 htmlhtml" 

我開蟒蛇的文檔,並嘗試自己做,但我甚至無法匹配的標籤。這個任務對於正則表達式來說似乎是非常常見的情況。

+0

這是Django的?你得到的錯誤是什麼?如果是django,你是否事先在模板中做了{%load static%}? – elethan

+0

是的,它是django,我想手動完成並將我的文件放到字符串中,以防止django每次嘗試從磁盤讀取它。原因是該文件太小,而且客戶經常要求他。 –

+0

我無法使用緩存,因爲我根本不需要緩存,我的網站只有一個頁面,通過使用Angular REST API繼續與網站進行交互。 –

回答

1

您可以使用Django的內置方法或一個簡單的正則表達式來實現相同的:

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 


見工作 demo on ideone.com

+0

非常感謝。你能給我一些鏈接來學習Python中的正則表達式嗎? –

+0

@LuchkoSerega很高興工作。一個好的起點是http://stackoverflow.com/documentation/python/632/regular-expressions-regex#t=201610261924366282161 – Jan

0

這裏是我想出了使用正則表達式您提供的信息示例解決方案:

>>> 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 '