HackerRank Solution: Python String Validators [4 Methods]


Hacker Rank Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Question: String Validators [Python Strings]

Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.

str.isalnum()

This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).

>>> print 'ab123'.isalnum()
True
>>> print 'ab123#'.isalnum()
False

str.isalpha()

This method checks if all the characters of a string are alphabetical (a-z and A-Z).

>>> print 'abcD'.isalpha()
True
>>> print 'abcd1'.isalpha()
False

str.isdigit()

This method checks if all the characters of a string are digits (0-9).

>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False

str.islower()

This method checks if all the characters of a string are lowercase characters (a-z).

>>> print 'abcd123#'.islower()
True
>>> print 'Abcd123#'.islower()
False

str.isupper()

This method checks if all the characters of a string are uppercase characters (A-Z).

>>> print 'ABCD123#'.isupper()
True
>>> print 'Abcd123#'.isupper()
False

Task

You are given a string S.
Your task is to find out if the string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.

Input Format

A single line containing a string S.

Constraints

0 < len(s) <100
Output Format

In the first line, print True if S has any alphanumeric characters. Otherwise, print False.
In the second line, print True if S has any alphabetical characters. Otherwise, print False.
In the third line, print True if S has any digits. Otherwise, print False.
In the fourth line, print True if S has any lowercase characters. Otherwise, print False.
In the fifth line, print True if S has any uppercase characters. Otherwise, print False.

Sample Input

qA2

Sample Output:

True
True
True
True
True

 

Possible Solutions

Now we will go through some of the possible solutions to the given question. We already have been given by the following code in the Hacker Rank:

if __name__ == '__main__':
    s = input()

Now let us solve the problem using various possible solutions:

 

Solution-1: Using if-else statements

Let us first use the if-else statements to solve the problem.

if __name__ == '__main__':
    s = input()

res = False
for i in s:
    if i.isalnum():
        res = True
        break
print(res)

res = False
for j in s:
    if j.isalpha():
        res = True
        break
print(res)

res = False
for k in s:
    if k.isdigit():
        res = True
        break
print(res)

res = False
for l in s:
    if l.islower():
        res = True
        break
print(res)

res = False
for l in s:
    if l.isupper():
        res = True
        break
print(res)
            

This Solution is checking if a string entered by the user contains alphanumeric characters, alphabetical characters, numerical characters, lowercase characters or uppercase characters. The input string is stored in the variable s and for each character in s, the code checks if the character is alphanumeric (using isalnum), alphabetical (using isalpha), numerical (using isdigit), lowercase (using islower) or uppercase (using isupper). If any character satisfies the condition, the value of res is set to True and the loop breaks. The final value of res is printed for each of the checks.

 

Solution-2: Using for loop

Now we will use only one for loop to solve the problem and then will explain the code.

if __name__ == '__main__':
    s = input()

strr = list(s)

al_num = False
al = False
dig = False
low = False
upp = False

for i in strr:
    al_num = al_num or i.isalnum() 
    al  = al or i.isalpha()
    dig = dig or i.isdigit()
    low = low or i.islower()
    upp = upp or i.isupper()

print(al_num)
print(al)
print(dig)
print(low)
print(upp)

The solution also checks various characteristics of the string entered by the user. The string is first converted into a list of characters and assigned to the variable "strr". Five variables, al_num, al, dig, low, and upp, are defined and initialized to False. The for loop then iterates over each character in the list and sets the corresponding variable to True if the string has an alphanumeric character, an alphabet, a digit, a lowercase letter, or an uppercase letter, respectively. Finally, the script outputs the results of the tests.

 

Solution-3: Using map and lambda function

We can even reduce the code using the map and lambda function as shown below:

if __name__ == '__main__':
    s = input()

    print(True in list(map(lambda n:n.isalnum(),s)))
    print(True in list(map(lambda n:n.isalpha(),s)))
    print(True in list(map(lambda n:n.isdigit(),s)))
    print(True in list(map(lambda n:n.islower(),s)))
    print(True in list(map(lambda n:n.isupper(),s)))

Similar to the previous solutions, this solutions also checks various characteristics of the string entered by the user. The script takes a string input from the user and applies the "isalnum", "isalpha", "isdigit", "islower", and "isupper" functions to each character in the string using the "map" function. The results of the tests are then passed to the "in" operator with True, which returns True if any of the characters in the string satisfies the corresponding test. Finally, the script outputs the results of the tests.

 

Solution-4: Using any() method

We can also use the any() method to check the string as shown below:

if __name__ == '__main__':
  string = input()

# Check for alphanumeric characters
  print(any(c.isalnum() for c in string))

# Check for alphabetical characters
  print(any(c.isalpha() for c in string))

# Check for digits
  print(any(c.isdigit() for c in string))

# Check for lowercase characters
  print(any(c.islower() for c in string))

# Check for uppercase characters
  print(any(c.isupper() for c in string))

This code is similar to the previous solutions, but it uses the "any" function instead of the "in" operator and list comprehension instead of the "map" function. The "any" function returns True if any element in the provided iterable (here, the result of the list comprehension) is True, while the "in" operator only returns True if the specified value (here, True) is found in the iterable. This solution is more concise and efficient than the previous ones. Additionally, the use of list comprehensions simplifies the code and reduces its line count.

 

Summary

In this short article, we discussed how we can solve the String Validator on hacker rank using various solutions. We discussed mainly four different kinds of solutions and explained each of them.

 

Further Reading

Question on Hacker Rank: String Validators [Python Strings]

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment