Last active
September 22, 2023 16:39
-
-
Save zxexz/3a0fa34643205a402db92bf12d5e5596 to your computer and use it in GitHub Desktop.
Ever been told strings are immutable in Python? I wanted to test that.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
def replace_contents( | |
string: str, | |
search_string: str, | |
replace_string: str = "", | |
global_replace: bool = False, | |
terminate_char: str = ' ', | |
return_type: type = str, | |
memoryview_cast: str = '@c' | |
): | |
from sys import (getsizeof) | |
from itertools import (chain, repeat) | |
from ctypes import (memset, cast, POINTER, c_char) | |
TRAILING = 1 | |
LEADING = getsizeof(str()) - TRAILING | |
while True: | |
if not len(search_string): | |
break | |
try: | |
for offset, character in ( | |
zip( | |
range( | |
string.index(search_string), | |
len(string) | |
), | |
map( | |
ord, | |
chain( | |
replace_string, | |
repeat( | |
terminate_char, | |
len(search_string) - len(replace_string) | |
) | |
) | |
) | |
) | |
): | |
memset( | |
id(string) + LEADING + offset, | |
character, | |
1 | |
) | |
except ValueError: | |
break | |
if not global_replace: | |
break | |
if return_type is str: | |
return string | |
elif return_type is memoryview: | |
return memoryview( | |
cast( | |
id(string) + LEADING, | |
POINTER( | |
c_char * (sys.getsizeof(string) - LEADING - TRAILING) | |
) | |
)[0] | |
).cast(memoryview_cast) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty sure this only works with CPython, of course...