Open In App

Python program to reverse alternate characters in a string

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, reverse its alternate characters string.

Input : test_str = ‘geeks4rgeeks’ 
Output : keekr4sgeegs 
Explanation : only g, e, s, r, e, k are reversed, rest all have same position.

Input : test_str = ‘geeks’ 
Output : egkes 

Method #1 : Using loop + slicing + reversed()

This is one of the ways in which this task can be performed. In this, we extract alternates using slicing and then reverse the string using reversed. The reconstruction of the string is done using a loop.

Python3




# Python3 code to demonstrate working of
# Alternate characters reverse in String
# Using loop + slicing + reversed()
 
# initializing string
test_str = 'geeks4rgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# extracting alternate string
alt = test_str[::2]
not_alt = test_str[1::2]
 
# performing reverse
alt = "".join(reversed(alt))
 
res = ''
# remaking string
for idx in range(len(alt)):
    res += alt[idx]
    res += not_alt[idx]
     
# printing result
print("Is alternate reversed string : " + str(res))


Output

The original string is : geeks4rgeeks
Is alternate reversed string : keekr4sgeegs

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using list comprehension

This is one more way in which this task can be performed. In this, we perform a similar function as above by using one-liner functionality using list comprehension.

Python3




# Python3 code to demonstrate working of
# Alternate characters reverse in String
# Using list comprehension
 
# initializing string
test_str = 'geeks4rgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# using one-liner to solve the problem
res = "".join(["".join(reversed(test_str[::2]))[idx] + test_str[1::2][idx]
      for idx in range(len("".join(reversed(test_str[::2]))))])
     
# printing result
print("Is alternate reversed string : " + str(res))


Output

The original string is : geeks4rgeeks
Is alternate reversed string : keekr4sgeegs

Time Complexity: O(n)

Auxiliary Space: O(n)

Method#3: Using join() and zip()

Python3




test_str = 'geeks4rgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# extracting alternate string
alt = test_str[::2]
not_alt = test_str[1::2]
 
# performing reverse
alt = "".join(reversed(alt))
 
# remaking string
res = "".join([x + y for x, y in zip(alt, not_alt)])
 
# printing result
print("Is alternate reversed string : " + str(res))
#This code is contributed by Vinay pinjala.


Output

The original string is : geeks4rgeeks
Is alternate reversed string : keekr4sgeegs

Time Complexity: O(n)

Auxiliary Space: O(n)

Method#4: Using loop and string concatenation.

Python3




# Python3 code to demonstrate working of
# Alternate characters reverse in String
# Using loop and string concatenation.
def alternate_reverse(string):
    res = ''
    for i in range(len(string)):
        if i % 2 == 0:
            res = string[i + 1] + res
        else:
            res = string[i - 1] + res
    return res
 
test_str = 'geeks4rgeeks'
# printing original string
print("The original string is : " + str(test_str))
res=alternate_reverse(test_str)
# printing result
print("Is alternate reversed string : " + str(res))
#this code contributed by tvsk


Output

The original string is : geeks4rgeeks
Is alternate reversed string : kseergs4ekge

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #5 : Using regular expressions

  1. Import the re module.
  2. Define a regular expression pattern that matches alternating groups of two characters in the string.
  3. Define a function that takes a match object as its argument and returns the reversed version of the match group.
  4. Use the re.sub() function to replace the matched groups in the string with their reversed version.
  5. Return the modified string.

Python3




# Python3 code to demonstrate working of
# Alternate characters reverse in String
# Using regular expressions
 
# import the re module
import re
 
# initializing string
test_str = 'geeks4rgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# define a regular expression pattern that matches alternating groups of two characters
pattern = r'(.)(.)'
 
# define a function to reverse the matched group
def reverse_match(match_obj):
    return match_obj.group(2) + match_obj.group(1)
 
# use re.sub() function to replace the matched groups in the string with their reversed version
res = re.sub(pattern, reverse_match, test_str)
 
# printing result
print("Is alternate reversed string : " + str(res))


Output

The original string is : geeks4rgeeks
Is alternate reversed string : egke4sgreesk

Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(n), as we need to create a new string to store the modified string.



Similar Reads

Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #1 : Using loop + slicing In this, we perform task
5 min read
Python | Alternate Sort in String list
Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression + sorted() This task can be achieved by using comb
2 min read
Python | Alternate vowels and consonants in String
Sometimes, while working with Strings in Python, we can have a problem in which we may need restructure a string, adding alternate vowels and consonants in it. This is a popular school-level problem and having solution to this can be useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop + join() + zip_longes
7 min read
Python | Alternate cases in String
The problem of case changes a string is quite common and has been discussed many times. Sometimes, we might have a problem like this in which we need to convert the odd character of string to upper case and even positioned characters to lowercase. Let’s discuss certain ways in which this can be performed. Method #1 : Using upper() + lower() + loop
5 min read
Python - Convert Alternate String Character to Integer
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the alternate list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem. Method #1 : Naive Method This is most generic method that strikes any programmer while performing t
5 min read
Python Program to reverses alternate strings and then concatenates all elements
Given a String List of length N, 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
6 min read
Python Program For Reversing Alternate K Nodes In A Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6->9->8->7->NULL. Method 1 (Process 2k node
6 min read
Python Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
7 min read
Python Program to Get Sum of cubes of alternate even numbers in an array
Given an array, write a program to find the sum of cubes of alternative even numbers in an array. Examples: Input : arr = {1, 2, 3, 4, 5, 6} Output : Even elements in given array are 2,4,6 Sum of cube of alternate even numbers are 2**3+6**3 = 224 Input : arr = {1,3,5,8,10,9,11,12,1,14} Output : Even elements in given array are 8,10,12,14 Sum of cub
5 min read
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Practice Tags :