Skip to main content

How to check if a string is numeric in Python

How to check if a string is numeric in Python.

Here's a detailed step-by-step tutorial on how to check if a string is numeric in Python:

Step 1: Understand the Problem

The problem is to determine whether a given string represents a numeric value or not. A numeric value can include integers, floating-point numbers, and numbers in scientific notation.

Step 2: Approach

To solve this problem, we can use a combination of built-in Python functions and methods to check if the string can be converted to a numeric value. We will use exception handling to catch any errors that occur during the conversion process.

Step 3: Check if the String is Numeric

Here are multiple code examples to check if a string is numeric in Python:

Example 1: Using isdigit() method

def is_numeric(string):
return string.isdigit()

# Test Cases
print(is_numeric("123")) # True
print(is_numeric("abc")) # False
print(is_numeric("12.3")) # False

Example 2: Using isdecimal() method

def is_numeric(string):
return string.isdecimal()

# Test Cases
print(is_numeric("123")) # True
print(is_numeric("abc")) # False
print(is_numeric("12.3")) # False

Example 3: Using isnumeric() method

def is_numeric(string):
return string.isnumeric()

# Test Cases
print(is_numeric("123")) # True
print(is_numeric("abc")) # False
print(is_numeric("12.3")) # False

Example 4: Using try-except block with float() function

def is_numeric(string):
try:
float(string)
return True
except ValueError:
return False

# Test Cases
print(is_numeric("123")) # True
print(is_numeric("abc")) # False
print(is_numeric("12.3")) # True

Example 5: Using regular expressions (regex)

import re

def is_numeric(string):
pattern = r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$'
return bool(re.match(pattern, string))

# Test Cases
print(is_numeric("123")) # True
print(is_numeric("abc")) # False
print(is_numeric("12.3")) # True

Step 4: Evaluate the Results

The above code examples will return True if the given string represents a numeric value, and False otherwise. You can test the code with different input strings to ensure its correctness.

That's it! You now have multiple code examples to check if a string is numeric in Python.