0

i am new to python programing, and was wondering if anyone could help me with encoding a message. for example if my dictionary is {'x': 'e', 'e': 'x'} and i would like to encode 'hello world' so that is prints 'hxllo world'

In [  ]: encode(code, "Hello World")
Out[  ]: 'Hxllo World'
5
  • 1
    Unless this is homework which stipulates the use of a dictionary, it is more elegant to use the string method translate. See this: tutorialspoint.com/python/string_translate.htm Commented Jun 26, 2016 at 14:37
  • yes i came across it on an exercise file which asks to use a dictionary to complete the task Commented Jun 26, 2016 at 14:40
  • What is code in encode, is that just the dictionary? Commented Jun 26, 2016 at 14:44
  • Using a dictionary, there is a 1-line answer of the from return ''.join(...) where ... is replaced by an appropriate comprehension. Commented Jun 26, 2016 at 14:44
  • @RoadRunner yes it is Commented Jun 26, 2016 at 14:46

2 Answers 2

1

You can do that using translate like so:

  1. define your dictionary
  2. use str.translate() to create translation table transtable
  3. finally do "mystring".translate(transtable)
  4. 'hxllo world', which is the required output

this makes use of the dictionary you are required to use. Just pass that dictionary as your code to your function encode.

Sign up to request clarification or add additional context in comments.

Comments

0

You could do something like this:

def encode(code, string):
    result = ""
    for char in string:
        if char in code:
            result += code[char]
        else:
            result += char
    return result

Output:

>>> print(encode(d, "Hello World"))
Hxllo World

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.