[SOLVED] How to control length of the result of string.format(bool_value) in Python?

Issue

What the equivalent way to str.format function for converting booleans into strings?

>>> "%5s" % True
' True'

>>> "%5s" % False
'False'

Please note the space in ' True'. This always makes the length the same for ‘True’ and ‘False’.

I’ve check the methods in this post:

How are booleans formatted in Strings in Python?

None of them can do the same thing.

Solution

I found that "{:>5}".format(str(True)) works fine.
The output is exactly the same as "%5s" % True, ie ' True'.

So the length of "{:>5}".format(str(bool_value)) is alway 5, no matter bool_value is True or False.

Of course you may change the length or the alignment direction as you want. eg. "{:6}".format(str(True)) outputs 'True '.

Answered By – Syrtis Major

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *