Home > Net >  How to print alternate elements in string using python
How to print alternate elements in string using python

Time:10-04

  • 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]

CodePudding user response:

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

CodePudding user response:

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'
  • Related