0

I need to rearrange a string with this sequence: 2,4,6 ... 1, 3, 5 For example 'Hello Joe' would become 'el oHloJ' This is my code:

def encrypt(message):
    newMessage = []
    for i in range(1, len(message), 2):
        newMessage.append(message[i])
    for i in range(0,len(message),2):
        newMessage.append(message[i])

    print(newMessage)

encrypt("Hello Jo")

I was wondering if there was a more efficient way to do this? Thanks.

2
  • What should happen if the given string has an uneven number of characters? Commented Apr 24, 2020 at 10:55
  • For uneven characters: input: 'end' output 'ned' Commented Apr 24, 2020 at 10:56

2 Answers 2

2

You can try the indexing feature, like :

def encrypt(message):
    new_message = message[1::2] + message[0::2]
    print(new_message)

encrypt("Hello Jo")
Sign up to request clarification or add additional context in comments.

1 Comment

He is basically doing the same thing you are doing with the range command. 'abc'[::2] for example, will return 'ac'. The third parameter when using indexing (just as range) is the "step" of the iterator. So when he say [1::2] He's saying: Start at index 1, go to the end of the string, and use a step-distance of 2.
1

you can use string built-in indexing features like this I hope this is what you are trying to achieve.

   In [2]: a ="Hello Jo"

    In [5]: a[1::2] + a[0::2]
    Out[5]: 'el oHloJ'

Hope it helps

first param in[::] is from where to start where as last param in which next item to take.

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.