Skip to content

Instantly share code, notes, and snippets.

@douzo
Last active July 12, 2023 04:59
Show Gist options
  • Save douzo/d4556e093db91f4dccb9ac4a2f8e5fb0 to your computer and use it in GitHub Desktop.
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
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