![]() |
When you’re using true or false values in Python, changing them to “Yes” or “No” strings can make your code easier to read. This article shows different ways to do it, giving you choices based on how you like to write your code. Here, we will convert the Python Boolean values to string as Yes or No instead of True or False. Convert Python boolean values to String (Yes or No)Below are some ways by which we can convert Python Boolean values into String in Python:
Convert Python boolean values to String Using if-else StatementsIn this example, a boolean variable `bool_val` is converted to the string “Yes” if it’s `True` and “No” if it’s `False` using if-else statements. Python3
Output
Original boolean value: True Converted string: Yes Pytho Boolean to Yes or No String Using Lambda FunctionIn this example, we are using lambda functions to convert a list of strings where “Yes” represents `True` and “No” represents `False`. A lambda function `lambda x: “Yes” if x else “No”` is applied to each element using the `map` function, resulting in the list `string_values`. Python3
Output
Original boolean value: [True, False, True, True, False] Converted string: ['Yes', 'No', 'Yes', 'Yes', 'No'] Boolean to Python String Using List ComprehensionIn this example, a list `bool_values` containing boolean elements is converted to a list of strings using a list comprehension. Each boolean element is transformed into “Yes” if it’s `True`, and “No” if it’s `False`. Python3
Output
Original boolean value: [True, False, True, True, False] Converted string: ['Yes', 'No', 'Yes', 'Yes', 'No'] Convert Boolean to Python String Using map() FunctionIn this example, boolean values are converted into string using map() function. Here, the `map` function and lambda function is applied to each boolean element, converting ‘True’ to “Yes” and ‘False’ to “No”. Python3
Output
Original boolean value: [True, False, True] Converted string: ['Yes', 'No', 'Yes'] |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |