Reverse a string preserving space positions | Python3 program to implement the above approach ; Initialize two pointers as two corners ; Move both pointers toward each other ; If character at start or end is space , ignore it ; If both are not spaces , do swap ; Driver code
def preserveSpace ( Str ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE Str = list ( Str ) NEW_LINE start = 0 NEW_LINE end = n - 1 NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( Str [ start ] == ' ▁ ' ) : NEW_LINE INDENT start += 1 NEW_LINE continue NEW_LINE DEDENT elif ( Str [ end ] == ' ▁ ' ) : NEW_LINE INDENT end -= 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT Str [ start ] , Str [ end ] = ( Str [ end ] , Str [ start ] ) NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT DEDENT print ( ' ' . join ( Str ) ) NEW_LINE DEDENT Str = " internship ▁ at ▁ geeks ▁ for ▁ geeks " NEW_LINE preserveSpace ( Str ) ; NEW_LINE