The Wayback Machine - https://web.archive.org/web/20241126223324/https://www.geeksforgeeks.org/python-string-isnumeric-method/
Open In App

Python String isnumeric() Method

Last Updated : 11 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The isnumeric() method is a built-in method in Python that belongs to the string class. It is used to determine whether the string consists of numeric characters or not. It returns a Boolean value. If all characters in the string are numeric and it is not empty, it returns “True” If all characters in the string are numeric characters, otherwise returns “False”.

Example: In this given string we will check string contains numeric characters or not.

Python3




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


Output:

True

Python String isnumeric() Method Syntax

Syntax:  string.isnumeric()

Parameters: isnumeric() does not take any parameters

Returns :

  • True – If all characters in the string are numeric characters.
  • False – If the string contains 1 or more non-numeric characters.

Ways to Implement the isnumeric() Method in Python

In Python, there are different libraries, functions, and methods to check if strings contain numeric characters. Here are the different ways in which we can use Isnumeric method.

Checking numeric/non-numeric characters using isnumeric() Method in Python

Python3




string = '123ayu456'
print(string.isnumeric())
 
string = '123456'
print(string.isnumeric())


Output: 

False
True

We can use various methods to check if the string contains numeric characters or not. To check this we can use different approach to solve this.

Counting and Removing numeric characters

In this example, the isnumeric() method is used to check the number of numeric characters and the resulting string after removing numeric characters.

Python3




# Given string
string = '123geeks456for789geeks'
count = 0
new_string = ""
 
for ch in string:
    if ch.isnumeric():
        count += 1
    else:
        new_string += ch
 
print("Number of numeric characters:", count)
print("String after removing numeric characters:", new_string)


Output: 

Number of numeric characters: 9
String after removing numeric characters: geeksforgeeks

Errors and Exceptions

It does not contain any arguments, therefore, it returns an error if a parameter is passed.

Python3




# isnumeric() returns an error if a parameter is passed
String = "1234567"
 
try:
    String.isnumeric("abc")
except TypeError:
    print("TypeError: isnumeric() takes no arguments (1 given)")


Output

TypeError: isnumeric() takes no arguments (1 given)

White spaces are not considered to be numeric, therefore, it returns “False”.

Python3




# isnumeric() to check White-spaces
s = " "
p = "12 3"
 
print(s.isnumeric())  # False
print(p.isnumeric())  # False
# This code is contributed by Susobhan Akhuli


Output

False
False

Subscript, Superscript, Fractions, and Roman numerals (all written in Unicode)are all considered to be numeric, Therefore, it returns “True”.

Python3




string1 = '123'
string2 = '⅓'
string3 = '²'
string4 = '2167'  # 'Ⅷ'; ROMAN NUMERAL EIGHT
 
print(string1.isnumeric())  # True
print(string2.isnumeric())  # True
print(string3.isnumeric())  # True
print(string4.isnumeric())  # True


Output

True
True
True
True

Combining isnumeric() with conditions

In this example, the isnumeric() method is used to check if the string “75” consists of only numeric characters.

Python3




string = '75'
if string.isnumeric() and int(string) > 50:
    print("Valid Number")
else:
    print("Invalid Number")


Output: 

Valid Number

String isnumeric() with another numeric type

The isnumeric() method in Python is primarily designed to work with strings. In this example, we can see the isnumeric() method may not directly support other numeric types like integers or floats, but still can utilize in combination with type conversion to perform numeric validation

Python3




# integer validation
number = 75
string = str(number)
result = string.isnumeric()
print(result)
 
# float validation
number = 5.65
string = str(number)
result = string.replace('.', '', 1).isnumeric()
print(result)


Output: 

True
True


Previous Article
Next Article

Similar Reads

numpy string operations | isnumeric() function
numpy.core.defchararray.isnumeric(arr) function returns true for each element if there are only numeric characters and there is at least one character.It returns false otherwise. Parameters: arr : array_like of str or unicode. Returns : [ndarray] Output array of bools. Code #1 : # Python program explaining # numpy.char.isnumeric() method import num
1 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Python String isspace() Method
Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ‘ ‘ – Space‘\t’ – Horizontal tab‘\n’ – Newline‘\v’ – Vertical tab‘\f’ – Feed‘\r’ – Carriage returnPython String isspace()
2 min read
Python String isprintable() Method
Python String isprintable() is a built-in method used for string handling. The isprintable() method returns "True" if all characters in the string are printable or the string is empty, Otherwise, It returns "False". This function is used to check if the argument contains any printable characters such as: Digits ( 0123456789 )Uppercase letters ( ABC
3 min read
Python String splitlines() Method
Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional). Syntax: string.splitlines([keepends]) Parameters: keepends (optional): When set to True line breaks are included in the resulting list. This can be a number, specifying the position
2 min read
Python String center() Method
Python String center() method creates and returns a new string that is padded with the specified character. Syntax: string.center(length[, fillchar]) Parameters: length: length of the string after padding with the characters.fillchar: (optional) characters which need to be padded. If it's not provided, space is taken as the default argument. Return
2 min read
Python String istitle() Method
Python String istitle() Method is a built-in string function that returns True if all the words in the string are title cased, otherwise returns False. Python String istitle() Method Syntax Syntax: string.istitle() Returns: True if the string is a title-cased string otherwise returns False. Python String istitle() Method Example C/C++ Code string =
2 min read
Python string isdecimal() Method
Python String isdecimal() function returns true if all characters in a string are decimal, else it returns False. In this article, we will explore further the isdecimal() method, understand its functionality, and explore its practical applications in Python programming. Python String isdecimal() SyntaxSyntax: string_name.isdecimal(), string_name is
2 min read
Python string swapcase() Method
Python String swapcase() method converts all uppercase characters to lowercase and vice versa of the given string and returns it. Syntax: string_name.swapcase() Parameter: The swapcase() method does not take any parameter. Return Value: The swapcase() method returns a string with all the cases changed. Example Below is the Python implementation of
1 min read
Python String partition() Method
Python String partition() method splits the string at the first occurrence of the separator and returns a tuple containing the part before the separator, the separator, and the part after the separator. Here, the separator is a string that is given as the argument. Example: C/C++ Code str = "I love Geeks for geeks" print(str.partition(
3 min read
Python String rindex() Method
Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises ValueError. Python String index() Method Syntax Syntax: str.rindex(sub, start, end) Parameters: sub : It’s the substring which needs to be searched in the given string.start : Starting position where sub is need
2 min read
Python String isidentifier() Method
Python String isidentifier() method is used to check whether a string is a valid identifier or not. The method returns True if the string is a valid identifier, else returns False. Python String isidentifier() method Syntax Syntax: string.isidentifier() Parameters: The method does not take any parameters Return Value: The method can return one of t
2 min read
Python String rsplit() Method
Python String rsplit() method returns a list of strings after breaking the given string from the right side by the specified separator. Python String rsplit() Method Syntax: Syntax: str.rsplit(separator, maxsplit) Parameters: separator: The is a delimiter. The string splits at this specified separator starting from the right side. If not provided t
2 min read
Python String rfind() Method
Python String rfind() method returns the rightmost index of the substring if found in the given string. If not found then it returns -1. Python String rfind() Method Syntax Syntax: str.rfind(sub, start, end) Parameters: sub: It’s the substring that needs to be searched in the given string. start: Starting position where the sub needs to be checked
3 min read
Python String rpartition() Method
Python String rpartition() Method split the given string into three parts. rpartition() starts looking for separator from the right side, till the separator is found and return a tuple which contains part of the string before separator, the separator and the part after the separator. Python String rpartition() Method Syntax Syntax : string.rpartiti
2 min read
Python String format_map() Method
Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key's value. Syntax: string.format_map(z) Parameters: Here z is a variable in which the input dictionary is stored and string is the key of the input dictionary. input_dict: Takes a single parameter which is the input dictionary. Returns: Return
2 min read
Python String isupper() method
Python String isupper() method returns whether all characters in a string are uppercase or not. Python String isupper() method Syntax Syntax: string.isupper() Returns: True if all the letters in the string are in the upper case and False if even one of them is in the lower case. Python String isupper() method Examples C/C++ Code Output: TrueExample
2 min read
Python String translate() Method
Python String translate() returns a string that is a modified string of givens string according to given translation mappings. What is translate() in Python?translate() is a built-in method in Python that is used to replace specific characters in a string with other characters or remove them altogether. The translate() method requires a translation
4 min read
Python string | capwords() method
In Python, string capwords() method is used to capitalize all the words in the string using split() method. Syntax: string.capwords(string, sep=None) Return Value: Returns a formatted string after above operations. Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the opt
2 min read
Python String maketrans() Method
Python String maketrans() function is used to construct the transition table i.e specify the list of characters that need to be replaced in the whole string or the characters that need to be deleted from the string. Syntax: maketrans(str1, str2, str3) Parameters: str1: Specifies the list of characters that need to be replaced.str2: Specifies the li
2 min read
Python String rjust() Method
Python String rjust() method returns a new string of a given length after substituting a given character on the left side of the original string. Python String rjust() Method Syntax Syntax: string.rjust(length, fillchar) Parameters: length: length of the modified string. If length is less than or equal to the length of the original string then orig
2 min read
Practice Tags :
three90RightbarBannerImg