How to check if a unicode string contains only numeric characters in Python?


In this article, we are going to find out how to check if a Unicode string contains only numeric characters in Python.

We will use the inbuilt function isnumeric() to check if there are only numeric characters present in a string. It is similar to isdigit() and isdecimal() but it has a wider range of acceptance.

It returns true for numbers, superscripts, subscripts, Fractions, Roman Numerals, etc. We can also use isdigit() and isdecimal() but isnumeric() is more efficient than the other two.

Example 1

In the example given below, we are taking a Unicode string as input and we are checking if the given Unicode string has only numeric characters using the isnumeric() function 

str1 = u"124345"

print("The given string is")
print(str1)

print("Checking if the given Unicode string contains only numeric characters")
res = str1.isnumeric()
print(res)

Output

The output of the above example is given below −

The given string is
124345
Checking if the given unicode string contains only numeric characters
True

Example 2

In the example given below, we are taking the same program as above but we are taking another string as input and checking if that Unicode string contains only numeric characters 

str1 = u"1243!@45"

print("The given string is")
print(str1)

print("Checking if the given Unicode string contains only numeric characters")
res = str1.isnumeric()
print(res)

Output

The output of the above example is as shown below −

The given string is
1243!@45
Checking if the given unicode string contains only numeric characters
False

Updated on: 07-Dec-2022

606 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements