Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 665
Syrtis Major Avatar asked Sep 18 '25 16:09

Syrtis Major


2 Answers

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. It also works with f-strings:

f'{True:_>5}'   # '____1'
f'{True!s:_>5}' # '_True'

Relevant documentation:

6.1.3. Format String Syntax

[...]

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.

Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

Some examples:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first
"More {!a}"                      # Calls ascii() on the argument first
like image 199
Michael Avatar answered Sep 20 '25 06:09

Michael


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
like image 21
jan Avatar answered Sep 20 '25 05:09

jan