Python String isnumeric() Method – Tutorial with Examples

Python String isnumeric() Method

In Python, strings are a sequence of characters. The isnumeric() method is a built-in method that can be used to check whether a given string contains only numeric characters or not. A numeric character can be a digit from 0-9, or a character from other number systems like Arabic, Roman numerals, and others.

Syntax

The syntax of the isnumeric() method is as follows:

string.isnumeric()

Here, string is the string that we want to check for numeric characters.

Return Value

The isnumeric() method returns True if all the characters in the string are numeric. Otherwise, it returns False.

Examples

Here are three different examples of how to use the isnumeric() method in Python:

Example 1: Checking if a String is Numeric

The following example demonstrates how to use the isnumeric() method to check if a given string contains only numeric characters:

string = "12345"
result = string.isnumeric()
print(result)

Output:

True

In this example, we define a string “12345” and use the isnumeric() method to check whether it contains only numeric characters. Since all the characters in the string are numeric, the method returns True.

Example 2: Checking if a String is Not Numeric

The following example demonstrates how to use the isnumeric() method to check if a given string contains non-numeric characters:

string = "1234abc"
result = string.isnumeric()
print(result)

Output:

False

In this example, we define a string “1234abc” and use the isnumeric() method to check whether it contains only numeric characters. Since the string contains non-numeric characters, the method returns False.

Example 3: Checking if a String is Numeric in a Different Number System

The following example demonstrates how to use the isnumeric() method to check if a given string contains only numeric characters in a different number system, such as Arabic or Roman numerals:

string = "ⅤⅠⅠ"
result = string.isnumeric()
print(result)

Output:

True

In this example, we define a string “ⅤⅠⅠ” which represents the Roman numeral “7”, and use the isnumeric() method to check whether it contains only numeric characters. Since the string contains only numeric characters, the method returns True.

Use Cases

The isnumeric() method can be useful in a variety of scenarios, such as:

  • Validating user input to ensure that it only contains numeric characters
  • Checking if a given string represents a numeric value before converting it to a number
  • Extracting numeric data from textual data sources, such as web pages or log files
  • Filtering out non-numeric characters from a string

Overall, the isnumeric() method provides a convenient and easy way to check whether a given string contains only numeric characters or not.

Leave a Reply

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