NubmcNub
NubmcNub

Reputation: 105

string replace using a list with a for loop

I am new to python and I want to replace characters in a string with with characters from a list for example.

tagFinder = ['<', '>','&']
safeTag = ['&lt;','&gt','&amp']

for i in content:
    return content.replace(tagFinder[i],safeTag[i]

I keep getting the following error

TypeError: list indices must be integers, not str

could someone please help a brother out thanks in advance!

Upvotes: 0

Views: 173

Answers (2)

Abhijit
Abhijit

Reputation: 63707

You probably intended

for i in range(len(tagFinder)):
    content = content.replace(tagFinder[i],safeTag[i])
..........
return content

instead of

for i in content:
    return content.replace(tagFinder[i],safeTag[i])

and also you are prematurely exiting the loop because of the return statement. The return statement should be the last statement in your function, assuming these statements are in a function

but then it is always better to use the built-in zip here

for src, dest in zip(tagFinder , safeTag ):
    content = content.replace(src, dest)
..........
return content

but then, unless this is part of a homework, you should use the standard library to escape your html string. In this particular case, cgi will be useful.

>>> import cgi
>>> cgi.escape(data).encode('ascii', 'xmlcharrefreplace')
'&lt;&gt;&amp;'

Upvotes: 3

bosnjak
bosnjak

Reputation: 8614

If you insist in doing it manually:

tagFinder = ['<', '>','&']
safeTag = ['&lt;','&gt','&amp']

for tag, safe in zip(tagFinder, safeTag):
    content = content.replace(tag, safe)

But there is a better way to escape HTML characters in Python:

import cgi
content = cgi.escape(content)

Upvotes: 0

Related Questions