python - string replace using a list with a for loop -


i new python , want replace characters in string with characters list example.

tagfinder = ['<', '>','&'] safetag = ['&lt;','&gt','&amp']  in content:     return content.replace(tagfinder[i],safetag[i] 

i keep getting following error

typeerror: list indices must integers, not str

could please brother out in advance!

you intended

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

instead of

for in content:     return content.replace(tagfinder[i],safetag[i]) 

and prematurely exiting loop because of return statement. return statement should last statement in function, assuming these statements in function

but better use built-in zip here

for src, dest in zip(tagfinder , safetag ):     content = content.replace(src, dest) .......... return content 

but then, unless part of homework, should use standard library escape html string. in particular case, cgi useful.

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

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -