How could I convert Python's old-style formatting strings, like this:
print("You: %s points. Me: %s points." % (score, total - score))
into the following?
print(f"You: {score} points. Me: {total - score} points.")
In fact, for the case of two %s
, I have written this regular expression:
"(.*)%s(.*)%s(.*)" % \(([^,\)]+), ([^,\)]+)\)
f"$1{$4}$2{$5}$3"
One could easily write several other regexes for handling the 1, 3, 4, ... %s
's cases, but I am looking for a more general and error-prone approach.
Note: AFAIK, a similar question was asked here in 2013 (Automatic conversion of the advanced string formatter from the old style), when the f-strings were not a thing (they were introduced in Python 3.6).
Essentially, you have three options; The first is to define a new line as a string variable and reference that variable in f-string curly braces. The second workaround is to use os. linesep that returns the new line character and the final approach is to use chr(10) that corresponds to the Unicode new line character.
Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string. For example, "This" is a string whereas f"This" is an f-String.
F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces.
Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol.
Use flynt
. You call it with the name of a directory and it recursively searches for all .py files and converts %
formatting to f-strings.
flynt <directory_to_process>
It will convert .format()
calls as well as %
formatting.
You can install it with
pip install flynt
Be warned that converting %
to f-strings is not perfect and will produce a different result if you were passing a single element tuple into them (which is why Python moved away from %
formatting).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With