Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are booleans formatted in Strings in Python?

People also ask

How do you make a Boolean a string in Python?

Use the bool() Function to Convert String to Boolean in Python. We can pass a string as the argument of the function to convert the string to a boolean value. This function returns true for every non-empty argument and false for empty arguments.

How do you print a boolean in string format?

In Java, to print any value, we use the System. out. println() method that works for boolean value as well, but if we want to print any formatted output to the console, then we use the printf() method. This method is similar to the printf() function of the C language.

How is string formatting done in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

How do you display boolean in Python?

Print Boolean values of different data types in PythonUse the built-in bool() method to print the value of a variable.


>>> print "%r, %r" % (True, False)
True, False

This is not specific to boolean values - %r calls the __repr__ method on the argument. %s (for str) should also work.


If you want True False use:

"%s %s" % (True, False)

because str(True) is 'True' and str(False) is 'False'.

or if you want 1 0 use:

"%i %i" % (True, False)

because int(True) is 1 and int(False) is 0.


You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language


To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'