pwtools.common.template_replace

pwtools.common.template_replace(txt, dct, conv=False, warn_mult_found=True, warn_not_found=True, disp=True, mode='dct')[source]

Replace placeholders dct.keys() with string values dct.values() in a text string. This function adds some bells and whistles such as warnings in case of not-found placeholders and whatnot.

Parameters:
  • txt (string with placeholders) –

  • dct (dictionary with placeholders (keys) and values to replace them) –

  • conv (bool, convert values dct.values() to strings with frepr()) –

  • warn_mult_found (bool, warning if a key is found multiple times in txt) –

  • warn_not_found (bool, warning if a key is NOT found in txt) –

  • disp (tell which keys have been replaced) –

  • mode (str, {'dct', 'txt'}, placeholder mode) –

    ‘dct’Dictionary mode. Placeholders are of special Python dictionary

    string replacement form: ‘%(<name>)<format_str>’, e.g. ‘%(foo)s’ and dct.keys() must be normal strings, e.g. ‘foo’. dct.values() can be anything. The conversion to a string is done at replacement time and determined by the <format_str>. This effectively does txt % dct. This method is faster, uses Python standard syntax and is therefore default.

    ’txt’Text mode. Placeholders in txt and keys in dct are the

    exact same arbitrary string (e.g. ‘XXXFOO’ in both). Here, dct.values() must be strings. If not, use conv=True to automatically convert them to strings, but note that this is limited since only frepr(<val>) is used.

Return type:

new string

Examples

>>> txt = 'XXXONE  XXXPI'
>>> dct = {'XXXONE': 1, 'XXXPI': math.pi}
>>> template_replace(txt, dct, conv=True, mode='txt')
'1  3.1415926535897931e+00'
>>>
>>> dct = {'XXXONE': '1', 'XXXPI': '%.16e' %math.pi}
>>> template_replace(txt, dct, mode='txt')
'1  3.1415926535897931e+00'
>>>
>>> txt = '%(one)s  %(pi).16e'; dct = {'one': 1, 'pi': math.pi}
>>> template_replace(txt, dct)
'1  3.1415926535897931e+00'
>>>
>>> txt % dct
'1  3.1415926535897931e+00'