Skip to content

Instantly share code, notes, and snippets.

@optinsoft
Created June 26, 2025 15:30
Show Gist options
  • Select an option

  • Save optinsoft/3160f8f81e9d610a0fe000b3c13be38f to your computer and use it in GitHub Desktop.

Select an option

Save optinsoft/3160f8f81e9d610a0fe000b3c13be38f to your computer and use it in GitHub Desktop.
replace placeholders enclosed in curly braces, like {thread}, {thread%10}, {thread/10}, with values
class NumReplacer(dict):
def __init__(self, **kwargs):
dict.__init__(self, **kwargs)
def __missing__(self, key):
karr = key.split('%')
if (len(karr) == 2) and karr[1].isdigit():
value = dict.get(self, karr[0], None)
if not value is None:
mod = int(karr[1])
return str(value % mod)
karr = key.split('/')
if (len(karr) == 2) and karr[1].isdigit():
value = dict.get(self, karr[0], None)
if not value is None:
div = int(karr[1])
return str(value // div)
return "{" + key + "}"
def replace_num(s: str, **kwargs) -> str:
return s.format_map(NumReplacer(**kwargs))
def main():
print(replace_num("{thread},{regnum},{unknown}", thread=3, regnum=13))
print(replace_num("{thread%10},{regnum%10},{unknown%10}", thread=5, regnum=23))
print(replace_num("{thread/10},{regnum/10},{unknown/10}", thread=7, regnum=37))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment