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

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

>>> "%5s" % 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.

  • I think "{:>5}".format(str(True)) works fine. OK, I'll leave this question here. Maybe someone will meet the same problem. – Syrtis Major Apr 12 '16 at 12:27
  • 5
    Post it as answer if you think it solved your case. – Iron Fist Apr 12 '16 at 12:31

You can use type conversion flags to do what you wanted:

'{:_>5}'.format(True)   # Oh no! it's '____1'
'{!s:_>5}'.format(True) # Now we get  '_True'

Note the !s. I used an underscore to show the padding more clearly.

Relevant documentation:

6.1.3. Format String Syntax




Some examples:


You can use the str() function. More about it here.

Here are some examples:

x = str(True)
y = False

print( type(x) )
<class 'str'>   # This is a string

print( type(y) )
<class 'bool'>  # This is a boolean

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


Not sure if I got idea correctly but if some variable x results in True or False, You can write str(x); if not a case, sorry just try explaining Q in more detailed way

Your Answer

