def reverse_alternate_groups(s):
groups = []
current_group = ""
is_letter = s[0].isalpha() # Determine if the first character is a letter or digit
# Step 1: Split the input string into groups of continuous letters and digits
for char in s:
if char.isalpha() == is_letter: # Same type (letter or digit)
current_group += char
else: # Type changes (letter to digit or digit to letter)
groups.append(current_group) # Store the completed group
current_group = char # Start a new group
is_letter = char.isalpha() # Update the type
groups.append(current_group) # Append the last group
# Step 2: Reverse every alternate group of letters
for i in range(len(groups)):
if i % 2 == 0 and groups[i][0].isalpha(): # Reverse if the group is letters and at even index
groups[i] = groups[i][::-1]
# Step 3: Join the groups back into a single string
return ''.join(groups)
# Example usage
input_str = "abc123def456ghi789jkl"
output_str = reverse_alternate_groups(input_str)
print(output_str) # Output: "cba123def456ihg789jkl"
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter