Nested f-strings

I don’t think formatted string literals allowing nesting (by nesting, I take it to mean f'{f”..”}’) is a result of careful consideration of possible use cases, I’m more convinced it’s just allowed in order for them to conform with their specification. The specification states that they support full Python expressions* inside brackets. It’s also stated … Read more

How to print the sign + of a digit for positive numbers in Python

Use the new string format >>> ‘{0:+} number’.format(1) ‘+1 number’ >>> ‘{0:+} number’.format(-1) ‘-1 number’ >>> ‘{0:+} number’.format(-37) ‘-37 number’ >>> ‘{0:+} number’.format(37) ‘+37 number’ # As the questions ask for it, little trick for not printing it on 0 >>> number = 1 >>> ‘{0:{1}} number’.format(number, ‘+’ if number else ”) ‘+1 number’ >>> … Read more

How to format a QString?

You can use QString.arg like this QString my_formatted_string = QString(“%1/%2-%3.txt”).arg(“~”, “Tom”, “Jane”); // You get “~/Tom-Jane.txt” This method is preferred over sprintf because: Changing the position of the string without having to change the ordering of substitution, e.g. // To get “~/Jane-Tom.txt” QString my_formatted_string = QString(“%1/%3-%2.txt”).arg(“~”, “Tom”, “Jane”); Or, changing the type of the arguments … Read more

Can Python’s logging format be modified depending on the message log level?

I just ran into this issue and had trouble filling in the “holes” left in the above example. Here’s a more complete, working version that I used. Hopefully this helps someone: # Custom formatter class MyFormatter(logging.Formatter): err_fmt = “ERROR: %(msg)s” dbg_fmt = “DBG: %(module)s: %(lineno)d: %(msg)s” info_fmt = “%(msg)s” def __init__(self, fmt=”%(levelno)s: %(msg)s”): logging.Formatter.__init__(self, fmt) … Read more