Thursday, February 20, 2020

Python String isdigit() Method

The isdigit() method in Python String class is used to check if all the characters in the string are digits or not.

isdigit() method returns true if all characters in the string are digits and there is at least one character, false otherwise. This method works for only positive, unsigned integers and for superscripts or subscripts which are passed as unicode character.

Python isdigit method examples

1. Using isdigit() method to check if all the characters are digits or not.

str = '456'
print(str)
print(str.isdigit())

str = 'A12'
print(str)
print(str.isdigit())

Output

456
True
A12
False

2. Using isdigit() method with superscripts or subscripts. For such strings isdigit() method returns true.

str = '2\u2076'
print(str)
print(str.isdigit())

str = '4\u2082'
print(str)
print(str.isdigit())

Output

26
True
42
True

3. Using isdigit() method with negative numbers or decimal numbers. For such strings isdigit() method returns false.

str = '2.45'
print(str)
print(str.isdigit())

str = '-12'
print(str)
print(str.isdigit())

Output

2.45
False
-12
False

4- To check negative numbers or decimal numbers using Python isdigit() method, you need to remove the minus or a decimal character before checking.

Using lstrip() method you can remove the specified leading characters (used to remove ‘-’ sign here).

Using replace() method you can replace decimal character (replace decimal with no space here).

str = '-12'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

str = '2.45'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

str = '-0.657'
print(str.lstrip('-').replace('.', '', 1).isdigit())
print(str)

Output

True
-12
True
2.45
True
-0.657

Since String is immutable in Python so the original string remains unchanged.

That's all for this topic Python String isdigit() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. Check String Empty or Not in Python
  3. Python String join() Method
  4. Namespace And Variable Scope in Python
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Python Program to Find Factorial of a Number
  2. Operator Overloading in Python
  3. Abstraction in Python
  4. Volatile Keyword in Java With Examples
  5. Invoke Method at Runtime Using Java Reflection API
  6. Setting And Getting Thread Name And Thread ID - Java Program
  7. Dependency Injection Using factory-method in Spring
  8. HDFS Commands Reference List