![]() |
|
[Tut] How to Convert Bool (True/False) to a String in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Convert Bool (True/False) to a String in Python? (/thread-100023.html) |
[Tut] How to Convert Bool (True/False) to a String in Python? - xSicKxBot - 10-04-2022 How to Convert Bool (True/False) to a String in Python? 5/5 – (1 vote) Question: Given a Boolean value Code: TrueCode: FalseCode: "True"Code: "False"Note that this tutorial doesn’t concern “concatenating a Boolean to a string”. If you want to do this, check out our in-depth article on the Finxter blog. Simple Bool to String Conversion To convert a given Boolean value to a string in Python, use the Code: str(boolean)Code: TrueCode: "True"Code: FalseCode: "False"Here’s a minimal example: Code: >>> str(True) 'True'
>>> str(False) 'False'Booleans are represented by integers in Python, i.e., Code: boolCode: intCode: TrueCode: 1Code: FalseHere’s a minimal example: Code: >>> True == 1
True
>>> False == 0
TrueTo convert a Boolean value to a string Code: '1'Code: '0'Code: str(int(boolean))Code: str(int(True))Code: '1'Code: str(int(False))Code: '0'Here’s a minimal example: Code: >>> str(int(True)) '1'
>>> str(int(False)) '0'To convert a Boolean to a string list, use the list comprehension expression Code: [str(x) for x in my_bools]Code: my_boolsCode: xCode: str()Code: xHere’s a simple example: Code: my_bools = [True, True, False, False, True]
my_strings = [str(x) for x in my_bools]
print(my_strings)
# ['True', 'True', 'False', 'False', 'True']What if you want to convert the string representation Code: 'True'Code: 'False'Code: '1'Code: '0'Code: TrueCode: False Recommended Tutorial: String to Boolean ConversionHere’s the short summary: You can convert a string value Code: sCode: bool(s)For example, Code: bool('True')Code: bool('1')Code: TrueHowever, Code: bool('False')Code: bool('0')Code: False This is because all Python objects are “truthy”, i.e., they have an associated Boolean value. As a rule of thumb: empty values return Boolean Code: TrueCode: FalseCode: bool('')Code: ''Code: FalseCode: TrueYou can see this in the following example: Code: >>> bool('True')
True
>>> bool('1')
True
>>> bool('2')
True
>>> bool('False')
True
>>> bool('0')
True
>>> bool('')
FalseOkay, what to do about it? Easy – first pass the string into the Code: eval()Code: bool()Code: bool(eval(my_string))Code: 'True'Code: '1'Code: TrueCode: 'False'Code: '0'Code: FalseFinally – this behavior is as expected by many coders just starting out. Here’s an example: Code: >>> bool(eval('False'))
False
>>> bool(eval('0'))
False
>>> bool(eval('True'))
True
>>> bool(eval('1'))
TrueFeel free to go over our detailed guide on the function: Recommended Tutorial: Python Code: eval() |