Home > Software engineering >  How do I replace letters in text using a dictionary?
How do I replace letters in text using a dictionary?

Time:10-16

I have a dictionary that looks like this:

Letters = {'a': 'z', 'b': 'q', 'm':'j'}

I also have a block of random text.

How do I get replace the letters in my text with the letter from the dictionary. So switch 'a' to 'z' and 'b' to 'q'.

What I've done so far is returning the wrong output and I can't think of any other way:

splitter = text.split()
res = " ".join(Letters.get(i,i) for i  in text.split())
print(res)

CodePudding user response:

You're iterating over the words in text, not over the letters in the words.

There's no need to use text.split(). Just iterate over text itself to get the letters. And then join them using an empty string.

res = "".join(Letters.get(i,i) for i  in text)

CodePudding user response:

What we can do is loop through each character in the string and add either the new character or the original character if the new character is not found.

text = "my text ba"
letters = {'a': 'z', 'b': 'q', 'm': 'j'}
result = ""

for letter in text: # For each letter in our string,
    result  = letters.get(letter, letter) # Either get a new letter, or use the original letter if it is not found.

If you want, you can also do this with a one-liner!

text = "my text ba"
letters = {'a': 'z', 'b': 'q', 'm': 'j'}
result = "".join(letters.get(letter, letter) for letter in text)

This is a bit confusing, so to break it down, for letter in text, we get either the new letter, or we use the (default) original letter.

You can see the documentation for the dict.get method here.

  • Related