Python program to check if a string has at least one letter and one number

Python program to check if a string has at least one letter and one number

Let's delve into a tutorial on how to check if a given string contains at least one letter and one number.

Objective:

Given a string, determine if it contains at least one alphabetical character and at least one numerical character.

Approach:

  1. Traverse each character of the string.
  2. Use Python's built-in methods isalpha() to check for alphabetical characters and isdigit() to check for numerical characters.
  3. Return True if both conditions are satisfied; otherwise, return False.

Step-by-step Implementation:

  1. Initialize two flags: We can initialize two boolean flags has_alpha and has_digit to False at the start.

    has_alpha = has_digit = False 
  2. Check each character:

    for char in input_string: if char.isalpha(): has_alpha = True if char.isdigit(): has_digit = True 
  3. Return the result:

    return has_alpha and has_digit 

Complete Program:

def check_string_content(input_string): # Initialize flags for letter and number has_alpha = has_digit = False # Check each character in the string for char in input_string: if char.isalpha(): has_alpha = True if char.isdigit(): has_digit = True # Return True if both flags are True; otherwise, return False return has_alpha and has_digit # Test the function test_string = "Hello123" print(f"Does the string '{test_string}' have at least one letter and one number? {check_string_content(test_string)}") # Expected output: True test_string2 = "123456" print(f"Does the string '{test_string2}' have at least one letter and one number? {check_string_content(test_string2)}") # Expected output: False 

Explanation:

  • For the test_string ("Hello123"), there are both numbers and letters in the string, so the function returns True.
  • For test_string2 ("123456"), there are only numbers, and no letters, so the function returns False.

Notes:

  • The function efficiently checks the string and can return as soon as both a letter and a number have been found, reducing the necessary computations.
  • The methods isalpha() and isdigit() are convenient built-ins provided by Python to identify the type of character without manually checking against character ranges.

More Tags

bluetooth-lowenergy svm sharedpreferences zooming bundler osx-mavericks angular2-services datamodel prompt

More Programming Guides

Other Guides

More Programming Examples