0

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!

2 Answers 2

3

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;'
Sign up to request clarification or add additional context in comments.

6 Comments

TypeError: 'int' object is not iterable - i get that as an error?
@NubmcNub: My bad. I have corrected the typographical error
thanks im almost there but when i return it i get this Expected :'&lt;p&gt;Hello World&lt;/p&gt;' Actual :'&amplt;p&ampgtHello World&amplt;/p&ampgt'
do i hae to escape the '&'?
Change the order of your tags such that tagFinder = ['&', '<', '>'] and safeTag = ['&amp', '&lt;','&gt']
|
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.