[英]Replacing characters in a string and returning in python
我使用Pycharm作為在python中進行編碼的軟件工具。
這些單詞為文本格式,但是應該返回不同的輸出
word = "<p>Santa is fat</p>"
secondword = "Potato & Tomato"
thirdword = "Koala eats http://koala.org/ a lot</p>"
我想將以下每個“ <”,““>”,“&”替換為 “ <
”,“ >
”,“ &
”
所以輸出應該像
outputword = "<p>Santa is fat</p>"
outputsecondword = "Fish & Chips"
outputthirdword = ""<p>Koala eats <a href='http://koala.org/'>http://koala.org/</a> a lot</p>"
注意,第三個單詞是URL。 我不想使用html庫。 我是Python的新手,請為我提供簡單的解決方案。 我考慮過使用列表,但是只要替換列表中的字符,它就不會改變
Python隨附電池 :
import html
word = "<p>Santa is fat</p>"
print(html.escape(word))
輸出:
<p>Santa is fat</p>
無需使用html
庫,您可以像這樣進行替換:
replacewith = {'<':'lt;', '>':'gt;'}
for w in replacewith:
word = word.replace(w,replacewith[w])
In [407]: word
Out[407]: 'lt;pgt;Santa is fatlt;/pgt;'
或者,一行:
word.replace('<','lt;').replace('>','gt;')
您可以將代碼移入函數並按如下方式調用它:
def replace_char(word, replacewith=replacewith):
for w in replacewith:
word = word.replace(w,replacewith[w])
return word
用下面的word
調用它會給你:
replace_char("<p>Santa is fat</p>")
Out[457]: 'lt;pgt;Santa is fatlt;/pgt;'
要使第二個字典起作用,請更新字典:
In [454]: replacewith.update({'Potato':'Fish', 'Tomato':'Chips', '&': '&',})
In [455]: replace_char("Potato & Tomato", replacewith)
Out[455]: 'Fish & Chips'
您可以以幾乎相同的方式對可能出現在其他新字符串中的任何新字符執行相同的操作。 您輸入的thirdword
在開頭缺少一個<p>
。
In [461]: replacewith.update({'http://koala.org/':'<a href="http://koala.org/">http://koala.org/</a>'})
In [463]: replace_char("Koala eats http://koala.org/ a lot</p>", replacewith)
Out[463]: 'Koala eats lt;a href="http://koala.org/"gt;http://koala.org/lt;/agt; a lotlt;/pgt;'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.