How to print alternate elements in string using python

Question:

  • I have one string ‘abcdef’

  • Need to print element like first element, last element, second element, second last element

  • Expected out is afbecd

  • Another output for abcde Expected is aebdc

  • Can we do it in without creating a extra list

pseudo code:

str1 = 'abcdef'
i= 0
j = 1
new_str = ''
while (i < len(str1) && j > len(str1) and i!=j):
   new_str = str1[i] + str1[j]
Asked By: abd

||

Answers:

With your approach you can do:

str1 = 'abcdef'
i= 0
j = len(str1) - 1
new_str = ''
while (j>i):
   new_str += str1[i] + str1[j]
   i+=1
   j-=1

if len(str1) % 2 != 0:
    new_str += str1[j]
print(new_str)

Output:

afbecd
Answered By: David Meu

Without any spurious memory usage, you can use some lazy iterators/generators with reversed and zip

def interleave(s):
    gen = (c for pair in zip(s, reversed(s)) for c in pair)
    return "".join(next(gen) for _ in s)

>>> interleave("abcdef")
'afbecd'
>>> interleave("abcde")
'aebdc'

You can introduce more utils to shorten the code even more:

from itertools import chain  

def interleave(s):
    gen = chain.from_iterable(zip(s, reversed(s)))
    return "".join(next(gen) for _ in s)
Answered By: user2390182

The way I see it, you have two possibilities based on string length here but they really only differ in how you handle the middle character. Therefore, an input of abcdefg should give you an output of agbfced whereas the output for abcdef would be afbecd.

Given the above, I think this should work:

def zip_str(input_str):
    width = len(input_str)
    half_width = int(width / 2)
    new_str = ""
    for i in range(0, half_width):
        new_str += input_str[i] + input_str[-1 - i]
    return new_str if width % 2 == 0 else new_str + input_str[half_width]
Answered By: Woody1193

A not particularly efficient but simple and imho fun way is to keep reversing the remaining string (Try it online!):

s = 'abcdef'

result = ''
while s:
   *s, char = reversed(s)
   result += char

print(result)

Or, since you actually say you want to print (Try it online!):

s = 'abcdef'

while s:
   *s, char = reversed(s)
   print(char, end='')
Answered By: no comment
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.