2

For a school project I have been trying to make a very very simple encryptor, however I am struggling with the encryption part. Basically I would like to have the encryption be every other letter starting from the first at the beginning and every other character at the end.

So 123456 would return as 135246

I am having trouble selecting every other letter after the first

def encrypt(message):
    return "%s%s" % (message[::-1],message[::2])

print(encrypt("123456"))

4 Answers 4

2

use following code

def encrypt(message):
   return "%s%s" % (message[::2],message[1::2])
Sign up to request clarification or add additional context in comments.

Comments

2

You could tweak your method a little as follows:

def encrypt(message):
    return "%s%s" % (message[::2],message[1::2])

print(encrypt("123456")) # 135246

Comments

1

Use slicing and indexing

msg = [1, 2, 3, 4, 5, 6]
In [30]: msg[::2] + msg[1::2]
Out[30]: [1, 3, 5, 2, 4, 6]

and for your function

def encrypt(message):
    return "%s%s" % (message[::2],message[1::2])

print(encrypt("123456"))

Comments

1

When you use message[::-1] you are actually commanding to display all the values in reverse. So expected output for message[::-1] will be 654321

So use

(message[::2],message[1::2])

This should work like a charm.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.