Python: Check if a string is a positive or negative integer

Date: 2024-12-11 | create | build | python |

Python has a lot of built-in helpers like isdigit to help you figure out what a value is. I recently ran into an issue where I needed to see if a value was a positive or negative integer but isdigit only handles positives.

So here's a little workaround to check if a string is a positive or a negative integer.

def is_positive_or_negative_integer(s: str) -> bool:
    return s[1:].isdigit() if s.startswith("-") else s.isdigit()

In tests:

test_cases = [
    ("-1", True),
    ("0", True),
    ("1", True),
    ("2", True),
    ("1.1", False),
    ("iamastring", False)
]

for test_case in test_cases:

    result = is_positive_or_negative_integer(test_case[0])
    is_pass = result == test_case[1]

    print(f"Pass: {is_pass} In: {test_case[0]} Out: {result} Expected: {test_case[1]}")

Outputs:

Pass: True In: -1 Out: True Expected: True
Pass: True In: 0 Out: True Expected: True
Pass: True In: 1 Out: True Expected: True
Pass: True In: 2 Out: True Expected: True
Pass: True In: 1.1 Out: False Expected: False
Pass: True In: iamastring Out: False Expected: False

Next

This isn't the most bulletproof code but it worked for my usecase and I'll probably need to do this again at some point so saving here for later.

If you want access to my full example project files, join HAMINIONs to get access to this example and dozens of others in Python and F#.

If you liked this post you might also like:

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.