H.G.
H.G.

Reputation: 35

How to make the first and the last characters become the first and the second character and so on

I am trying to create a function where it first makes your string backwards (so, "Hello,world" becomes "dlrow ,olleH") and then the first and the last characters become the first and the second character in the string, and the second and the second last characters become the third and the fourth characters in the string, and so on.

For example:

"Hello, world" becomes "dHlerlolwo ," (notice how all punctuation, special characters, spaces, etc are all treated the same)

"0123456789" becomes "9081726354".

So far all I know how to do is make the string backwards:

def encrypt(s):
    return s[::-1]

Upvotes: 0

Views: 583

Answers (2)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38982

Zip the message and the reversed message. Iterate over both and join to form a message of alternating characters in both messages.

def encrypt(message):
    reversed_message = reversed(message) # better than slicing for lazy evaluation

    alternating_chars = (
        ''.join((i, j)) 
        for i,j in zip(message, reversed_message)
    )
    alternating_chars = ''.join(
        list(alternating_chars)
    )

    return alternating_chars[:len(message)]

print encrypt('you can\'t start flying cars to try and get yourself noticed')

You may optimize the function early by zipping message and reverse message of length one more than half the original length.

Upvotes: 1

Alperen
Alperen

Reputation: 4642

Simply, add characters in a for loop:

def encrypt(s):
    reversed = s[::-1]
    ret_str = ""
    length = len(reversed)
    for i in range(length // 2):
        ret_str +=  reversed[i] +reversed[length - 1 - i]

    if(length % 2 == 1):
        ret_str += reversed[length // 2 + 1]
    return ret_str

print(encrypt("Hello, world"))
print(encrypt("0123456789")) 

Output:

dHlerlolwo ,
9081726354

Upvotes: 0

Related Questions