I'm using Pycharm as the software tool to code in python.
These words are in a text format but they are supposed to return different outputs
word = "<p>Santa is fat</p>"
secondword = "Potato & Tomato"
thirdword = "Koala eats http://koala.org/ a lot</p>"
I want to replace each of the following "<" , ">" , "&" to " <
" , " >
" , " &
"
So the output should look like
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>"
Notice that the third word is a URL. I dont want to use the html library. I'm a noob at Python so please provide me with simple solutions. I considered using lists but whenever I replace a character in the list, it doesn't change
Python comes with batteries included :
import html
word = "<p>Santa is fat</p>"
print(html.escape(word))
Output:
<p>Santa is fat</p>
Without using the html
library, you can do the replacements like this:
replacewith = {'<':'lt;', '>':'gt;'}
for w in replacewith:
word = word.replace(w,replacewith[w])
In [407]: word
Out[407]: 'lt;pgt;Santa is fatlt;/pgt;'
Or, in one line:
word.replace('<','lt;').replace('>','gt;')
You can move the code into a function and call it like this:
def replace_char(word, replacewith=replacewith):
for w in replacewith:
word = word.replace(w,replacewith[w])
return word
Calling it with word
like below will give you:
replace_char("<p>Santa is fat</p>")
Out[457]: 'lt;pgt;Santa is fatlt;/pgt;'
To get the second one to work, update the dictionary:
In [454]: replacewith.update({'Potato':'Fish', 'Tomato':'Chips', '&': '&',})
In [455]: replace_char("Potato & Tomato", replacewith)
Out[455]: 'Fish & Chips'
You can do the same for any new characters that may appear in other new strings in pretty much the same way. Your input thirdword
is missing a <p>
right at the beginning.
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;'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.