Open In App

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

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string in Python. The task is to check whether the string has at least one letter(character) and one number. Return “True” if the given string fully fill the above condition else return “False” (without quotes).

Examples: 

Input: welcome2ourcountry34
Output: True

Input: stringwithoutnum
Output: False

Approach: 

The approach is simple we will use loop and two flags for letter and number. These flags will check whether the string contains letter and number. In the end, we will take AND of both flags to check if both are true or not. Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method.

Python3




def checkString(str):
 
    # initializing flag variable
    flag_l = False
    flag_n = False
 
    # checking for letter and numbers in
    # given string
    for i in str:
 
        # if string has letter
        if i.isalpha():
            flag_l = True
 
        # if string has number
        if i.isdigit():
            flag_n = True
 
    # returning and of flag
    # for checking required condition
    return flag_l and flag_n
 
 
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))


Output

True
False

Time Complexity: O(n)
Auxiliary Space: O(n)

Approach: Without using builtin methods

Python3




def checkString(str):
 
    # initializing flag variable
    flag_l = False
    flag_n = False
     
    # checking for letter and numbers in
    # given string
    for i in str:
     
        # if string has letter
        if i in "abcdefghijklmnopqrstuvwxyz":
            flag_l = True
 
        # if string has number
        if i in "0123456789":
            flag_n = True
     
    # returning and of flag
    # for checking required condition
    return flag_l and flag_n
 
 
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))


Output

True
False

Time Complexity: O(n), where n is length of string.
Auxiliary Space: O(1)

Approach : Using operator.countOf() method

Python3




import operator as op
 
 
def checkString(str):
    letters = "abcdefghijklmnopqrstuvwxyz"
    digits = "0123456789"
 
    # initializing flag variable
    flag_l = False
    flag_n = False
 
    # checking for letter and numbers in
    # given string
    for i in str:
 
        # if string has letter
        if op.countOf(letters, i) > 0:
            flag_l = True
 
        # if string has digits
        if op.countOf(digits, i) > 0:
            flag_n = True
 
    # returning and of flag
    # for checking required condition
    return flag_l and flag_n
 
 
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))


Output

True
False

Time Complexity: O(N)
Auxiliary Space : O(1)

Approach : Using regular Expressions

Python3




import re
 
def checkString(str):
    # using regular expression to check if a string contains
    # at least one letter and one number
    match = re.search(r'[a-zA-Z]+', str) and re.search(r'[0-9]+', str)
    if match:
        return True
    else:
        return False
 
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))
#This code is contributed by Vinay Pinjala.


Output

True
False

Time Complexity: O(N)
Auxiliary Space : O(1)

Approach: Using  set intersection: 

 Algorithm:

1. Define a function “checkString” that takes a string “str” as input.
2. Create two sets – “letters” and “digits”, containing all the letters and digits respectively.
3. Check if the intersection of the input string and the sets of letters and digits is not empty using the ‘&’ operator.
4. Return True if both sets are not empty, otherwise return False.

Python3




def checkString(str):
    # Create sets of letters and digits
    letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    digits = set('0123456789')
    # Check if the intersection of the input string and the sets of letters and digits is not empty
    return bool(letters & set(str)) and bool(digits & set(str))
# Test the function with two sample inputs
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))
#This code is contributed by Jyothi pinjala.


Output

True
False

Time Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input string. This is because the sets of letters and digits are constant and have a small size, so their creation can be considered as a constant time operation.
Space Complexity:

The space complexity of the algorithm is O(1), as we are only using two sets to store the letters and digits, which have a constant size. The input string is not modified and no extra space is used to store the output.

Approach: Using lambda function 

In this approach, we are using a lambda function to check if the given string contains both letters and numbers. We use the all function to check if all the characters in the string satisfy the given condition, which is that the character should either be an alphabet or a digit. We generate a boolean value for each character in the string using a generator expression inside the all function. Finally, we return the result of all function from the lambda function.

Python3




checkString = lambda s: any(c.isalpha() for c in s) and any(c.isdigit() for c in s)
 
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))


Output

True
False

Time Complexity: O(n)
Space Complexity: O(1)



Similar Reads

Python | Ways to check if given string contains only letter
Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let's discuss a few methods to complete the task. Method #1: Using isalpha() method C/C++ Code # Python code to demonstrate # to find whether string contains # only letters # Initialising string ini_str = "ababababa" # Printing ini
3 min read
Python Program to Removes Every Element From A String List Except For a Specified letter
Given a List that contains only string elements, the following program shows methods of how every other alphabet can be removed from elements except for a specific one and then returns the output. Input : test_list = ["google", "is", "good", "goggled", "god"], K = 'g' Output : ['gg', '', 'g', 'ggg', 'g'] Explanation : All characters other than "g"
4 min read
Python regex to find sequences of one upper case letter followed by lower case letters
Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print 'Yes', otherwise 'No'. Examples: Input : GeeksOutput : YesInput : geeksforgeeksOutput : NoPython regex to find sequences of one upper case letter followed by lower case lettersUsing re.search() To check if the sequence of one upper case
2 min read
Python - Eliminate Capital Letter Starting words from String
Sometimes, while working with Python Strings, we can have a problem in which we need to remove all the words beginning with capital letters. Words that begin with capital letters are proper nouns and their occurrence mean different meaning to the sentence and can be sometimes undesired. Let's discuss certain ways in which this task can be performed
7 min read
Python Capitalize First Letter of Every Word in String
In text manipulation in Python, capitalizing the first letter of every word in a string is a common and essential task. This operation enhances the visual presentation of text and is particularly useful when dealing with user input, titles, or any scenario where proper capitalization is desired. In this article, we will explore some approaches to c
3 min read
Python | Check if two lists have at-least one element common
Given two lists a, b. Check if two lists have at least one element common in them. Examples: Input : a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output : True Input : a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9] Output : FalseMethod 1: Traversal of List Using traversal in two lists, we can check if there exists one common element at least in them. While traversing
5 min read
Python program to capitalize the first letter of every word in the file
The following article contains programs to read a file and capitalize the first letter of every word in the file and print it as output. To capitalize the first letter we will use different methods using Python. The Python String Method is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the
3 min read
Count the number of times a letter appears in a text file in Python
In this article, we will be learning different approaches to count the number of times a letter appears in a text file in Python. Below is the content of the text file gfg.txt that we are going to use in the below programs: Now we will discuss various approaches to get the frequency of a letter in a text file. Method 1: Using the in-built count() m
3 min read
Python program to check if any key has all the given list elements
Given a dictionary with list values and a list, the task is to write a Python program to check if any key has all the list elements. Examples: Input : test_dict = {'Gfg' : [5, 3, 1, 6, 4], 'is' : [8, 2, 1, 6, 4], 'best' : [1, 2, 7, 3, 9], 'for' : [5, 2, 7, 8, 4, 1], 'all' : [8, 5, 3, 1, 2]}, find_list = [7, 9, 2] Output : True Explanation : best ha
7 min read
Python | Find longest consecutive letter and digit substring
Given a String (may contain both letters and digits), write a Python program to find the longest consecutive letter and digit substring. Examples: Input : geeks123available Output : ('available', 123) Input : 98apple658pine Output : ('apple', 658) Approach #1 : Brute force This is the Naive or brute force approach to find the longest consecutive le
5 min read