chloe donohoe chloe donohoe - 1 year ago 82
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():


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?

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download