How to use XOR to swap two characters in a string in Python

1 Answer

0 votes
def xor_swap_characters(text_list: list[str], left: int, right: int) -> None:
    """
    Swaps two characters in a list of characters in-place using the XOR swap algorithm.

    This function demonstrates bitwise XOR swapping for educational purposes.
    In idiomatic Python, tuple assignment (text[left], text[right] = text[right], text[left])
    is strongly preferred for performance and readability.

    :param text_list: Mutable list of single-character strings.
    :param left: Zero-based index of the first character.
    :param right: Zero-based index of the second character.
    """
    length = len(text_list)

    # Bounds checking and negative index protection
    if length == 0 or left < 0 or left >= length or right < 0 or right >= length:
        return

    # XOR swap fails if left == right because (x ^ x) evaluates to 0
    if left == right:
        return

    # Convert characters to Unicode code points, apply XOR, and map back to chars
    text_list[left] = chr(ord(text_list[left]) ^ ord(text_list[right]))
    text_list[right] = chr(ord(text_list[right]) ^ ord(text_list[left]))
    text_list[left] = chr(ord(text_list[left]) ^ ord(text_list[right]))


def main() -> None:
    original = "hello"
    text_list = list(original)

    print(f"Before: {''.join(text_list)}")

    xor_swap_characters(text_list, 1, 4)

    result = "".join(text_list)
    print(f"After:  {result}")


if __name__ == "__main__":
    main()



'''
run:

Before: hello
After:  holle

'''

 



answered Sep 30 by avibootz
...