Last active
July 12, 2023 04:59
-
-
Save douzo/d4556e093db91f4dccb9ac4a2f8e5fb0 to your computer and use it in GitHub Desktop.
in the given string, reverse only the alphabets while keeping the integers in its original position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def reverse_alphabets(string): | |
# Separate alphabets and digits | |
alphabets = [] | |
digits = [] | |
for char in string: | |
if char.isalpha(): | |
alphabets.append(char) | |
else: | |
digits.append(char) | |
# Reverse the alphabets | |
reversed_alphabets = alphabets[::-1] | |
# Reconstruct the string | |
output = "" | |
for char in string: | |
if char.isalpha(): | |
output += reversed_alphabets.pop(0) | |
else: | |
output += char | |
return output | |
# Example usage | |
input_string = 'a1b2c3d4312' | |
output_string = reverse_alphabets(input_string) | |
print(output_string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment