string.octdigits in Python

In this tutorial, we are going to learn about the string.octdigits constant in Python.

The string.octdigits is a pre-defined string constant in the string module of Python. It contains all the octal digits (0-7) as a single string. We can use this constant whenever we need to work with octal digits in our program by simply importing it from the string module.

Basic Usage

Let's see what string.octdigits contains ?

import string

# Print the octal digits string
print(string.octdigits)
print("Length:", len(string.octdigits))
01234567
Length: 8

Checking the Data Type

The string.octdigits is a string object. You can verify this by checking its type ?

import string

# Check the type of octdigits
print(type(string.octdigits))
print("Is it a string?", isinstance(string.octdigits, str))
<class 'str'>
Is it a string? True

Practical Examples

Validating Octal Characters

You can use string.octdigits to check if a character is a valid octal digit ?

import string

def is_octal_digit(char):
    return char in string.octdigits

# Test with different characters
test_chars = ['0', '7', '8', '9', 'a', '5']
for char in test_chars:
    result = is_octal_digit(char)
    print(f"'{char}' is octal digit: {result}")
'0' is octal digit: True
'7' is octal digit: True
'8' is octal digit: False
'9' is octal digit: False
'a' is octal digit: False
'5' is octal digit: True

Filtering Octal Digits from a String

Extract only the octal digits from a mixed string ?

import string

def extract_octal_digits(text):
    return ''.join(char for char in text if char in string.octdigits)

# Test with a mixed string
mixed_string = "abc123def456ghi789"
octal_only = extract_octal_digits(mixed_string)
print(f"Original: {mixed_string}")
print(f"Octal digits only: {octal_only}")
Original: abc123def456ghi789
Octal digits only: 1234567

Comparison with Other Digit Constants

Constant Value Description
string.digits 0123456789 All decimal digits
string.octdigits 01234567 All octal digits
string.hexdigits 0123456789abcdefABCDEF All hexadecimal digits

Conclusion

The string.octdigits constant provides a convenient way to work with octal digits in Python. It's particularly useful for validation, filtering, and any operations that need to distinguish between octal digits (0-7) and other characters.

Updated on: 2026-03-25T09:03:25+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements