Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python f-strings: indentation for long strings?

I’m facing (aesthetic) problems with long f-string expressions in Python. For example, this code snippet

if __name__ == '__main__': 
    x_true = 3
    x_prov = 4

    assert x_prov == x_true, f'The provided value for x, namely {x_prov}, is invalid, \
    the true value should be {x_true}!'

gives the following error, which is totally expected, of course:

AssertionError: The provided value for x, namely 4, is invalid,     the true value should be 3!

There is an unwanted indentation in the error message that in my opinion looks very ugly, though. One way to circumvent this is to write

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if __name__ == '__main__': 
    x_true = 3
    x_prov = 4

    assert x_prov == x_true, f'The provided value for x, namely {x_prov}, is invalid, \
the true value should be {x_true}!'
    
    # Do sth else. 

However, this also looks ugly to me, as now the second line of the string has the same indentation as the outer '__main__' function. Is there a way to have the AssertionError displayed properly without having to indent the code as the outer function?

>Solution :

Yes, making use of implicit string concatenation, you can do this:

if __name__ == "__main__":
    x_true = 3
    x_prov = 4

    assert x_prov == x_true, (
        f"The provided value for x, namely {x_prov}, is invalid,"
        f" the true value should be {x_true}!"
    )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading