Reverse Alternate Characters in a String - Python
Last Updated :
13 May, 2025
Reversing alternate characters in a string involves rearranging the characters so that every second character is reversed while maintaining the original order of other characters. For example, given the string 'abcde', reversing the alternate characters results in 'ebcda', where the first, third and fifth characters ('a', 'c', 'e') are reversed and the second and fourth characters ('b', 'd') remain in place. Let's explore different methods to achieve this efficiently.
zip_longest() pair characters from two lists, ensuring that if one list is shorter, the remaining characters from the longer list are added without any errors. It’s like a smart assistant that makes sure no character is left behind.
Python
from itertools import zip_longest
s = 'abcde'
s1 = s[::2][::-1]
s2 = s[1::2]
res = ''.join(a + b if b else a for a, b in zip_longest(s1, s2))
print(res)
Explanation:
- s[::2][::-1] takes every second character starting from index 0 ('a', 'c', 'e') and reverses them to get s1 = 'eca'.
- s[1::2] takes every second character starting from index 1 ('b', 'd') to get s2 = 'bd'.
- zip_longest(s1, s2) pairs characters: 'e' with 'b', 'c' with 'd', and 'a' with None.
- Inside join(), a + b if b else a merges the pairs, resulting in 'ebcda'.
Using list comprehension
This method creates a new list by combining characters in one clean line of code. It’s neat and concise, like writing a quick, efficient to-do list .
Python
s = 'abcde'
s1 = s[::2][::-1]
s2 = s[1::2]
res = [s1[i] + s2[i] if i < len(s2) else s1[i] for i in range(len(s1))]
if len(s2) > len(s1):
res.append(s2[-1])
print(''.join(res))
Explanation:
- s[::2][::-1] takes every second character from index 0 ('a', 'c', 'e'), reverses it to 'eca'.
- s[1::2] takes every second character starting from index 1 ('b', 'd').
- List comprehension pairs characters from s1 and s2, merging them ('e' + 'b', 'c' + 'd') and adding any leftover characters from s1.
- If s2 is longer than s1, the remaining character(s) from s2 are appended, but in this case, it's skipped.
Using extend()
This method manually loops through both lists and pairs the characters one by one, adding them to a result list. It's like carefully picking out pieces and placing them in order. Afterward, it checks if there are any leftover characters and adds them.
Python
s = 'abcde'
s1 = list(s[::2])[::-1]
s2 = list(s[1::2])
res = []
for i in range(min(len(s1), len(s2))):
res.extend([s1[i], s2[i]])
res.extend(s1[i+1:] + s2[i+1:])
print(''.join(res))
Explanation:
- list(s[::2])[::-1] takes every second character from index 0 ('a', 'c', 'e'), then reverses the list to ['e', 'c', 'a'].
- list(s[1::2]) takes every second character starting from index 1 ('b', 'd'), resulting in ['b', 'd'].
- Loop through the shorter length (2 iterations), pairing characters from s1 and s2: ['e', 'b'] and ['c', 'd'], adding to res.
- After the loop, add remaining characters from s1 ('a') to res, resulting in 'ebcda'.
Related articles
Similar Reads
Alternate cases in String - Python The task of alternating the case of characters in a string in Python involves iterating through the string and conditionally modifying the case of each character based on its position. For example, given a string s = "geeksforgeeks", the goal is to change characters at even indices to uppercase and
3 min read
Remove Character in a String at a Specific Index in Python Removing a character from a string at a specific index is a common task when working with strings and because strings in Python are immutable we need to create a new string without the character at the specified index. String slicing is the simplest and most efficient way to remove a character at a
2 min read
Python - Reverse Shift characters by K Given a String, reverse shift each character according to its alphabetic position by K, including cyclic shift. Input : test_str = 'bccd', K = 1 Output : abbc Explanation : 1 alphabet before b is 'a' and so on. Input : test_str = 'bccd', K = 2 Output : zaab Explanation : 2 alphabets before b is 'z'
3 min read
Python - Right and Left Shift characters in String In string manipulation tasks, especially in algorithmic challenges or encoding/decoding scenarios, we sometimes need to rotate (or shift) characters in a string either to the left or right by a certain number of positions.For example, let's take a string s = "geeks" and we need to perform a left and
3 min read
Python - Reverse String except punctuations Given a string with punctuations, perform string reverse, leaving punctuations at their places. Input : test_str = 'geeks@#for&%%gee)ks' Output : skeeg@#rof&%%ske)eg Explanation : Whole string is reversed, except the punctuations. Input : test_str = 'geeks@#for&%%gee)ks' [ only substring
5 min read