## 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!