Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically convert old string formatting style into f-strings

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:

  • search: "(.*)%s(.*)%s(.*)" % \(([^,\)]+), ([^,\)]+)\)
  • replace: 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).

like image 879
Aristide Avatar asked May 13 '18 14:05

Aristide


People also ask

How do I change strings to f-string?

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.

How do you convert a string to an F-string in Python?

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.

What does %f do in Python?

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.

What is f-string formatting?

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.


1 Answers

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).

like image 52
Boris Avatar answered Sep 30 '22 02:09

Boris