October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Check if a String Represents a Boolean in Python

Python treats every non-empty string as true. Parse boolean text by explicitly mapping accepted tokens, and use argparse actions for presence-based flags.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python’s bool() does not read a string’s words: bool("False") is True because the string is non-empty. To check whether text represents a boolean, define which words your program accepts, convert those explicitly, and reject anything else.

Why bool("False") is True

bool() performs a truth-value test; it does not parse text as a boolean. An empty string is false, while every non-empty string is true, regardless of its contents. So bool("") is False, but bool("False"), bool("no"), and bool("0") are all True. The Python 3.13 argparse documentation specifically cautions against using bool() as a type converter for this reason.

Parse only the boolean words your input specification allows

If the accepted values are the words true and false, compare against those values directly. This parser ignores letter case and surrounding whitespace, but rejects other text:

def parse_bool(value: str) -> bool:
    normalized = value.strip().casefold()
    if normalized == "true":
        return True
    if normalized == "false":
        return False
    raise ValueError(f"Expected 'true' or 'false', got {value!r}")

For example, parse_bool(" TRUE ") returns True, and parse_bool("False") returns False. Values such as "yes", "0", or "maybe" raise ValueError unless you choose to support them.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose and document the vocabulary

There is no universal set of boolean words that every Python application must accept. If your interface should accept alternatives such as yes/no, 1/0, or on/off, add each token deliberately and map it to the intended value. Python’s argparse documentation describes choices as useful when an argument accepts a fixed set of values.

Reject invalid input rather than silently treating it as false

Returning False for every unrecognized string makes typos and malformed input look valid. Raise a clear exception, as above, or use another explicit result that lets the caller distinguish invalid input from a valid false value.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

For command-line flags, use argparse actions

When a command-line option is enabled simply by appearing, use store_true rather than asking the user to supply the word true or false:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args()

With this setup, --verbose sets args.verbose to True; leaving out the option sets it to False. The store_false action provides the inverse behavior. These actions are documented in the Python 3.13 argparse reference.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Offer positive and negative spellings

argparse.BooleanOptionalAction, available in Python 3.9 and later, creates positive and negative forms such as --feature and --no-feature. They set the destination to True and False, respectively. Check your project’s minimum supported Python version before using it.

When the command line must accept a text value

If users need to write an argument such as --enabled false, pass the supplied text through a validating parser with a documented vocabulary, or constrain it to fixed choices and convert it explicitly. Do not use type=bool: the non-empty string false converts to True, not False.

Choose based on what the input means

Input situation Use Behavior
Whether a CLI option was included argparse store_true or store_false Sets a boolean based on flag presence.
A CLI option with positive and negative forms argparse.BooleanOptionalAction Provides forms such as --feature and --no-feature; requires Python 3.9 or later.
Text that encodes a boolean An explicit parser or fixed choices followed by conversion Accepts only the tokens you define and can reject invalid text.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.