How to reverse a string without changing order of special characters (e.g. commas)?
Hussain Khawaja
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):
# Convert string to a list to modify characterss_list = list(s)# Find all alphanumeric characters (ignoring special ones)alnum_chars = [c for c in s_list if c.isalnum()]# Reverse only the alphanumeric charactersi = 0j = len(alnum_chars) - 1while i < len(s_list): if s_list[i].isalnum(): # Place reversed alphanumeric characters s_list[i] = alnum_chars[j] j -= 1 i += 1# Join the list back into a stringreturn ''.join(s_list)
# Convert string to a list to modify characters
s_list = list(s)
# Find all alphanumeric characters (ignoring special ones)
alnum_chars = [c for c in s_list if c.isalnum()]
# Reverse only the alphanumeric characters
i = 0
j = len(alnum_chars) - 1
while i < len(s_list):
if s_list[i].isalnum(): # Place reversed alphanumeric characters
s_list[i] = alnum_chars[j]
j -= 1
i += 1
# Join the list back into a string
return ''.join(s_list)
input_str = “a,b$c”result = reverse_string_keep_special(input_str)print(result) # Output will be: “c,b$a”