How do you check if a string contains only octal characters in Python?
Posted by HenryPk
Last Updated: August 29, 2024
To check if a string contains only octal characters in Python, you can utilize the set data structure or regular expressions. Octal characters are the digits from 0 to 7. Here are two effective methods to perform this check:
Method 1: Using set
You can leverage a set for efficient membership testing. This method involves creating a set of valid octal digits and then verifying that all characters in the string belong to this set.
def is_octal(string):
    octal_digits = {'0', '1', '2', '3', '4', '5', '6', '7'}
    return all(char in octal_digits for char in string)

# Example usage
test_string = "1234670"
print(is_octal(test_string))  # Output: True
Method 2: Using Regular Expressions
Another approach involves using regular expressions, which are powerful for pattern matching. The regular expression ^[0-7]+$ checks if the string contains only octal digits.
import re

def is_octal(string):
    return re.fullmatch(r'^[0-7]+$', string) is not None

# Example usage
test_string = "1234670"
print(is_octal(test_string))  # Output: True
Considerations
- Both methods assume that the input is a string. It's recommended to handle potential exceptions or validate the input type if necessary. - An empty string will return False in both methods, as it contains no valid octal characters. By using either of these methods, you can efficiently determine if a string consists solely of octal characters in Python.