Python String isnumeric() Method
Python String isnumeric() method returns “True” if all characters in the string are numeric characters, otherwise returns “False”.
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.
Python String isnumeric() Method Example
Python3
print ( "1299" .isnumeric()) |
Output:
True
This function is used to check if the argument contains all numeric characters such as integers, fractions, subscript, superscript, Roman numerals, etc.(all written in Unicode).
Example 1: Basic Examples using Python String isnumeric() Method
Python3
string = '123ayu456' print (string.isnumeric()) string = '123456' print ( string.isnumeric()) |
Output:
False True
Example 2: Checking for numeric characters using isnumeric() function
Application: Given a string in Python, count the number of numeric characters in the string and remove them from the string, and print the string.
Algorithm:
- Initialize an empty new_string and variable count to 0.
- Traverse the given string character by character up to its length, check if the character is a numeric character.
- If it is a numeric character, increment the counter by 1 and do not add it to the new string, else traverse to the next character and keep adding the characters to the new string if not numeric.
- Print the count of numeric characters and the new string.
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.
- Whitespaces are not considered to be numeric, therefore, it returns “False”
- Subscript, Superscript, Fractions, Roman numerals (all written in Unicode)are all considered to be numeric, Therefore, it returns “True”
Please Login to comment...