Use isdigit() Function in Python with Example

The `isdigit()` function in Python is a string method that checks if all the characters in a string are digits. It returns `True` if all characters are digits and there is at least one character, otherwise it returns `False`.

Syntax

string.isdigit()

Example

Here’s an example to demonstrate how to use the `isdigit()` function:

```python
# Example 1: All characters are digits
s1 = "12345"
print(s1.isdigit()) # Output: True

# Example 2: Contains non-digit characters
s2 = "12345a"
print(s2.isdigit()) # Output: False

# Example 3: Empty string
s3 = ""
print(s3.isdigit()) # Output: False

# Example 4: String with spaces
s4 = "123 456"
print(s4.isdigit()) # Output: False
# Example 5: Negative number (not considered a digit string)

s5 = "-12345"
print(s5.isdigit()) # Output: False
```

Explanation

1. Example 1: The string `”12345″` contains only digit characters, so `s1.isdigit()` returns `True`.
2. Example 2: The string `”12345a”` contains a non-digit character (`’a’`), so `s2.isdigit()` returns `False`.
3. Example 3: The empty string `””` does not contain any characters, so `s3.isdigit()` returns `False`.
4. Example 4: The string `”123 456″` contains spaces, which are not digits, so `s4.isdigit()` returns `False`.
5. Example 5: The string `”-12345″` contains a minus sign, so `s5.isdigit()` returns `False`.

Use Cases

The `isdigit()` method is useful when you want to validate that a string consists solely of digit characters before performing operations that require numeric input.