Skip to content

Instantly share code, notes, and snippets.

@zxexz
Last active September 22, 2023 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zxexz/3a0fa34643205a402db92bf12d5e5596 to your computer and use it in GitHub Desktop.
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.
#! /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)
@zxexz
Copy link
Author

zxexz commented Aug 1, 2019

Pretty sure this only works with CPython, of course...

@zxexz
Copy link
Author

zxexz commented Aug 1, 2019

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment