chloe donohoe chloe donohoe - 12 days ago 9
Python Question

How can I replace certain characters in a string?

I'm relatively new to python(3.5.2) and I'd love some help with my assignment on lists& strings.
I am required to write a code that replaces: e and E with 3, a and A with 4, i and I with 1, o and O with 0 in any given string. Here is my attempt:

s = input("Enter a string: ")

leet = {'a':'4','e':'3','i':'1','o':'0','A':'4','E':'3','I':'1','O':'0'}

for character in s:
if character == leet.keys():
str.replace(leet.keys(),leet.values())

print(s)


This code does not yield any satisfying results for me, I'm wondering if I can use the str.replace method or is there any easier way of doing this?
Thanks!

Answer

replace() method is good. But you use it wrong. Remember that leet.keys() will return a list of all keys in the dictionary. So I suggest this:

s = input("Enter a string: ")

leet = {'a': '4', 'e': '3', 'i': '1', 'o': '0', 'A': '4', 'E': '3', 'I': '1', 'O': '0'}

for k, v in leet.items(): #iterating through dictionary (not string)
    s = s.replace(k, v)

print(s)