Reverse Alternate Characters in a String – Python
We have to reverse the alternate characters in a given string. The task is to identify every second character in the string, reverse their order and keep the other characters unchanged.
For example, “abcd” needs to be changed to “cbad” and “abcde” needs to be changed to “ebcda”
This can be accomplished easily in Python using techniques like slicing, reversed(), list comprehension, join(), zip(), and regular expressions.
Example: 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.
s = 'abcde'
s1 = s[::2] # Chars at even indices
s2 = s[1::2] # Chars at odd indices
# reverse even index characters
s1 = "".join(reversed(s1))
# Merge till the shorter string length
res = ''
for idx in range(min(len(s1), len(s2))):
res += s1[idx]
res += s2[idx]
# Add remaining characters
res += s1[idx + 1:] + s2[idx + 1:]
print(str(res))
Output
ebcda
Explanation:
- Slicing is used to extract alternate characters from the original string.
- The reversed() function is applied on the alternate characters string (alt) to reverse the order.
- The loop is then used to recreate the original string by combining the reversed alternate characters and non-alternate characters.
Table of Content
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.
s = 'abcd'
print(str(s))
# using one-liner to solve the problem
rev = "".join(["".join(reversed(s[::2]))[idx] + s[1::2][idx]
for idx in range(len("".join(reversed(s[::2]))))])
print(str(rev))
Output
abcd cbad
Explanation:
- The method extracts alternate characters using slicing (s[::2]) and reverses them.
- Then, a list comprehension is used to rebuild the string by iterating over the indices of the reversed alternate characters and concatenating them with the corresponding non-alternate characters.
Using join() and zip()
In this code, we are using the approach of join() and the zip() function to reverse the alternate characters of a given string while keeping the other characters in their original order.
s = 'abcde'
print(str(s))
# extracting alternate string
s1 = s[::2]
s2 = s[1::2]
# performing reverse
s1 = "".join(reversed(s1))
# remaking string
rev = "".join([x + y for x, y in zip(s1, s2)])
# Handling odd length case where there's an extra character in s1
if len(s1) > len(s2):
rev += s1[-1]
print(str(rev))
Output
abcde ebcda
Explanation:
- This approach extracts the alternate characters and non-alternate characters.
- The reversed() function is applied to the alternate characters, and then the zip() function is used to pair corresponding characters from both lists (alt and not_alt).
Using loop and string concatenation
Here is the Python code to reverse alternate characters in a string using a loop and string concatenation approach:
def reverse(string):
rev = ''
s1 = string[::2]
s2 = string[1::2]
# Reverse the 's1' string using a loop
s1 = s1[::-1]
j = 0
for i in range(len(s2)):
rev += s1[j]
rev += s2[i]
j += 1
# If there are any remaining characters in 's1' (for odd length strings)
if j < len(s1):
rev += s1[j]
return rev
s = 'abcde'
print(s)
rev = reverse(s)
print(rev)
Output
abcde ebcda
Explanation:
- s1 = string[::2] Extracts characters at even indices (0, 2, 4,…).
- s2 = string[1::2] Extracts characters at odd indices (1, 3, 5,…).
- Reversing the s1 string: The even-indexed characters are reversed using slicing ([::-1]).
- The loop concatenates characters from the reversed s1 string and the s2 string (which remains unchanged).
- If the string length is odd, the last character from s1 is appended to the result.
Using regular expressions
In this code, we use regular expressions to reverse every alternate pair of characters in the given string.
import re
def fun(s):
# Extract even-indexed characters
e_char = [m.group(1) for m in re.finditer(r"(.).?", s)]
# Reverse them
rev = list(reversed(e_char))
# Extract odd-indexed characters
odd = [m.group(1) for m in re.finditer(r".(.)?", s) if m.group(1)]
# Interleave
inter = []
n = min(len(rev), len(odd))
for i in range(n):
inter.append(rev[i])
inter.append(odd[i])
# Handle odd-length strings
if len(rev) > len(odd):
inter.append(rev[-1])
# Join and return
return ''.join(inter)
# Example usage
s = "abcde"
print(fun(s))
Output
ebcda
Explanation:
- e_char extracts even-indexed chars (0, 2, 4…) with r”(.).?”.
- rev reverses those chars.
- odd extracts odd-indexed chars (1, 3, 5…) with r”.(.)?”.
- inter interleaves reversed even chars (rev) with unchanged odd chars (odd).
- Handles odd-length strings by appending the last even char if needed.