Monday 29 May 2023

Convert a string to boolean in Python

Using bool() method, we can convert a string to boolean in Python.

 

Example

bool_val = bool(input_str)

string_to_boolean.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

bool_val = bool(input_str)
print('bool_val : ', bool_val)

Output

Enter a string hello
input_str :  hello  type :  <class 'str'>
bool_val :  True

Following rules are followed while considering a value as True in Python.

 

a.   Any non-zero numeric value is considered as True. 0, 0.0 are evaluated to False

b.   Nom empty strings, dictionaries, lists, tuples, sets is considered as True. Empty strings (""), empty lists ([]), empty tuples (()) and empty sets ({}) are evaluated as False.

c.    Special value ‘None’ is considered as False

d.   Boolean True is considered as True, and False is considered as False.

 

bool_values.py

print("Following values evaluated to True")
print('bool("True") : ', bool("True"))
print('bool("false") : ', bool("false"))
print('bool("False") : ', bool("False"))
print('bool("Yes") : ', bool("Yes"))
print('bool("No") : ', bool("No"))
print('bool("0") : ', bool("0"))
print('bool("0.0") : ', bool("0.0"))
print('bool("1") : ', bool("1"))
print('bool([2, 3]) : ', bool([2, 3]))
print('bool({"id" : 1}) : ', bool({"id":1}))
print('bool(True) : ', bool(True))

print("\nFollowing values evaluated to False")
print('bool(0) : ', bool(0))
print('bool(0.0) : ', bool(0.0))
print('bool([]) : ', bool([]))
print('bool({}) : ', bool({}))
print('bool(()) : ', bool(()))
print('bool(set()) : ', bool(set()))
print('bool(None) : ', bool(None))
print('bool(False) : ', bool(False))

Output

Following values evaluated to True
bool("True") :  True
bool("false") :  True
bool("False") :  True
bool("Yes") :  True
bool("No") :  True
bool("0") :  True
bool("0.0") :  True
bool("1") :  True
bool([2, 3]) :  True
bool({"id" : 1}) :  True
bool(True) :  True

Following values evaluated to False
bool(0) :  False
bool(0.0) :  False
bool([]) :  False
bool({}) :  False
bool(()) :  False
bool(set()) :  False
bool(None) :  False
bool(False) :  False



 

Previous                                                 Next                                                 Home

No comments:

Post a Comment