1
Reply

How to reverse a string without changing order of special characters (e.g. commas)?

    To reverse a string without changing the order of special characters (e.g., commas, punctuation), you can follow this approach:Identify the alphanumeric characters in the string.
    Reverse only the alphanumeric characters while keeping the special characters in their original positions.

    def reverse_string_keep_special(s):

    1. # Convert string to a list to modify characters
    2. s_list = list(s)
    3. # Find all alphanumeric characters (ignoring special ones)
    4. alnum_chars = [c for c in s_list if c.isalnum()]
    5. # Reverse only the alphanumeric characters
    6. i = 0
    7. j = len(alnum_chars) - 1
    8. while i < len(s_list):
    9. if s_list[i].isalnum(): # Place reversed alphanumeric characters
    10. s_list[i] = alnum_chars[j]
    11. j -= 1
    12. i += 1
    13. # Join the list back into a string
    14. return ''.join(s_list)

    Example

    input_str = “a,b$c”
    result = reverse_string_keep_special(input_str)
    print(result) # Output will be: “c,b$a”