Search code examples
c++pythonwxwidgetsstring-formatting

wxString: Is there any C/C++ code that implements string formatting using Python3-like placeholders?


I am rewriting our application using wxWidgets. One of the goals is to replace our old approach to the localized strings. Another possible goal is to embed the Python interpreter to the application -- but only later. Anyway, it would be nice any C/C++ code or library capable of Python-like string formatting that uses the curly braces.

If you do not know Python, here is the doc for its format function. You can find the reference to the Format Specification Mini-Language inside, and the Format examples. Some extract from the doc... (The >>> is a prompt of the interactive Python mode, the line below shows the result of the call. Python uses single or double quotes as a string delimiter):

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

I would also like to use the Python formatting with the named placeholders (instead of numeric indices). In Python, the str.format_map(mapping) method of strings is used where the mapping is of the map<string, some_type> like type. Say, my_dictionary contains mapping like:

"name"    --> "Guido"
"country" --> "Netherlands"

Having a template string like below, I would like to get the result...

wxString template("{name} was born in {country}.");
wxString result(format_map(s, my_dictionary));

// the result should contain...
// "Guido was born in Netherlands."

Do you know any avaliable C or C++ code capable of that, or do I have to write my own?

Thanks for your time and experience,

Petr


Solution

  • Yes. The fmt library uses format string syntax based on Python's str.format. It supports most of the formatting options of str.format including named arguments. Here's an example:

    std::string s = fmt::format("{0}{1}{0}", "abra", "cad");
    // s == "abracadabra"
    

    Disclaimer: I'm the author of this library.