TaleOfGaming G
TaleOfGaming G

Reputation: 15

How do I replace letters in text using a dictionary?

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)

Upvotes: 1

Views: 842

Answers (3)

jetpack_guy
jetpack_guy

Reputation: 360

translation_table = str.maketrans({'a': 'z', 'b': 'q', 'm':'j'})
translated = your_text.translate(translation_table)

This is concise and fast

Upvotes: 1

Ayush Garg
Ayush Garg

Reputation: 2517

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.

Upvotes: 1

Barmar
Barmar

Reputation: 781721

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)

Upvotes: 0

Related Questions