Search code examples
pythonsplitpep8f-string

PEP8-conform splitting of long f-string


How to split the following long line into two lines, in order to conform to PEP8?

percentage = f"{state[0] / state[1] * 100:{3 + (decimals > 0) + decimals}.{decimals}f}%"

Note: The f-string here cannot simply be split into two f-strings as suggested in the accepted answer to a previously asked question, since this would break formatting. This question here hence needs a different and more general solution.


Solution

  • Don't be afraid of using variables! It will make your code more readable.

    a = state[0] / state[1] * 100
    b = 3 + (decimals > 0) + decimals
    # of course, you would change the names here
    percentage = f"{a:{b}.{decimals}f}%"