Validation in Python

Problem Statement:

We are given a string, we need to check whether the string is a valid username or not. To be a valid username, the string should satisfy the following conditions:

  • The string should only contain letters, numbers, or underscore(s).
  • It should not start with a number.
  • It should not end with an underscore.
  • Its length should be greater than equal to 4 and less than equal to 25.

Code for Validation in Python:

def check_username(s):
    alphabets = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    if (type(s[0]) != str):
        return 'Invalid Username1'
    
    if (len(s)<4):
        return 'Invalid Username2'
    
    if (len(s)>25):
        return 'Invalid Username3'
    
    if (s[-1] == '_'):
        return 'Invalid Username4'
    
    for i in s:
        if (i in alphabets) or (i == '_') or (i in numbers):
            continue
        return 'Invalid Username5'
    return 'Valid Username'

t = int(input('Enter number of test cases: '))
for i in range(t):
    s = input('\nEnter username: ')
    s = list(s)
    for i in range(len(s)):
        try:
            s[i] = int(s[i])
        except:
            continue
    print(check_username(s), '\n')

Output:

Output for Validation in Python

Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you