Skip to content
Related Articles

Related Articles

Improve Article

Python Program to reverses alternate strings and then concatenates all elements

  • Last Updated : 01 Jun, 2021

Given a String List, the following program returns a concatenated list of all its string elements with its alternate elements reversed.

Input : test_str = ‘geeksgeeks best for geeks’ 
Output : skeegskeeg best rof geeks 
Explanation : Alternate words reversed.
Input : test_str = ‘geeksgeeks best geeks’ 
Output : skeegskeeg best skeeg 
Explanation : Alternate words reversed. 

Method 1 : Using reversed() and loop

In this, we perform the task of reversing strings using reversed() and then check for alternates using % operator and concatenate accordingly.

Python3




# initializing string
test_str = 'geeksgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# splitting string
temp = test_str.split()
 
res = []
for idx in range(len(temp)):
     
    # reversing if alternate
    if idx % 2 == 0:
        res.append(''.join(list(reversed(temp[idx]))))
    else :
        res.append(temp[idx])
         
res = ' '.join(res)
 
# printing result
print("Transformed String : " + str(res))

Output:



The original string is : geeksgeeks is best for geeks

Transformed String : skeegskeeg is tseb for skeeg

Method 2 : Using slicing and list comprehension

In this, we perform task fo reversal using slicing and then list comprehension is used to perform the task done by loop, in shorthand.

Python3




# initializing string
test_str = 'geeksgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# splitting string
temp = test_str.split()
 
# list comprehension to solve problem in 1 liner
res = ' '.join([''.join(list(reversed(temp[idx]))) if idx % 2 == 0 else temp[idx] for idx in range(len(temp))])
 
# printing result
print("Transformed String : " + str(res))

Output:

The original string is : geeksgeeks is best for geeks

Transformed String : skeegskeeg is tseb for skeeg

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :