简体   繁体   中英

Replacing characters in a string and returning in python

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 " &lt; " , " &gt; " , " &amp; "

So the output should look like

outputword = "&lt;p&gt;Santa is fat&lt;/p&gt;"
outputsecondword = "Fish &amp; Chips"
outputthirdword = ""&lt;p&gt;Koala eats <a href='http://koala.org/'>http://koala.org/</a> a lot&lt;/p&gt;"

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:

&lt;p&gt;Santa is fat&lt;/p&gt;

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

Update:

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', '&': '&amp;',})
In [455]: replace_char("Potato & Tomato", replacewith)
Out[455]: 'Fish &amp; 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM