Python – Find digits in a given Number


To find out if a specific number (e.g., 5) is available in a given number (e.g., 12345678), you can use the following steps in a programming context:

Using a Programming Language:

  1. Convert the number to a string: Convert the given number to a string data type if it’s not already a string. This makes it easier to manipulate the individual digits.
  2. Iterate through the digits: Use a loop to iterate through each digit in the string representation of the number.
  3. Check for equality: Inside the loop, compare each digit to the number you’re looking for (in this case, 5). If you find a match, you can stop the loop and conclude that the number is available in the given number.

Related Post: Finding a Specific Digit in a Number using Java

Here’s a Python example:

SearchDigit.py
def is_number_available(given_number, target_digit):
    # Convert the given number to a string
    given_number_str = str(given_number)
    
    # Iterate through each digit
    for digit in given_number_str:
        # Check if the current digit is equal to the target digit
        if digit == str(target_digit):
            return True
    
    # If the loop finishes without finding a match, return False
    return False

# Example usage
given_number = 12345678
target_digit = 5

if is_number_available(given_number, target_digit):
    print(f"{target_digit} is available in {given_number}")
else:
    print(f"{target_digit} is not available in {given_number}")

And if we optimize the above function, the result would be:

def is_number_available(digit, number):
    # Convert the number to a string
    number_str = str(number)
    
    # Check if the digit is in the string representation of the number
    return str(digit) in number_str

References

  1. Text Sequence Type — str
  2. Setting Up a Python Development Environment on Windows, Mac, and Linux

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.