reverse digit in a series

PHOTO EMBED

Tue Dec 31 2024 05:03:23 GMT+0000 (Coordinated Universal Time)

Saved by @sooraz3871 #python

def reverse_digits_in_series(s):
    # Initialize an empty list to store the result
    result = []
    
    # Temporary list to store digits while iterating
    digits = []

    # Loop through each character in the input string
    for char in s:
        if char.isdigit():
            # If the character is a digit, add it to the digits list
            digits.append(char)
        else:
            # If the character is not a digit, process the digits collected so far
            if digits:
                # Reverse the digits list and add to the result
                result.append(''.join(digits[::-1]))
                digits = []  # Reset the digits list for next series
            # Append the non-digit character to the result as is
            result.append(char)
    
    # In case there are digits left at the end of the string
    if digits:
        result.append(''.join(digits[::-1]))

    # Join the result list into a string and return it
    return ''.join(result)

# Example usage
input_str_1 = "abc123def456gh"
output_str_1 = reverse_digits_in_series(input_str_1)
print(output_str_1)  # Output: "abc321def654gh"

input_str_2 = "1a2b3c"
output_str_2 = reverse_digits_in_series(input_str_2)
print(output_str_2)  # Output: "1a2b3c"
content_copyCOPY