close

How to check that a string contains only “a-z”, “A-Z” and “0-9” characters

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check that a string contains only “a-z”, “A-Z” and “0-9” characters in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How to check that a string contains only “a-z”, “A-Z” and “0-9” characters?

  1. How to check that a string contains only “a-z”, “A-Z” and “0-9” characters?

    The re.fullmatch() method allows to check if the whole string matches the regular expression pattern. Returns a corresponding match object if match found, else returns None if the string does not match the pattern.

  2. check that a string contains only “a-z”, “A-Z” and “0-9” characters

    The re.fullmatch() method allows to check if the whole string matches the regular expression pattern. Returns a corresponding match object if match found, else returns None if the string does not match the pattern.

Method 1

You could use regex for this, e.g. check string against following pattern:

import re
pattern = re.compile("[A-Za-z0-9]+")
pattern.fullmatch(string)

Explanation:

[A-Za-z0-9] matches a character in the range of A-Z, a-z and 0-9, so letters and numbers.

+ means to match 1 or more of the preceeding token.

The re.fullmatch() method allows to check if the whole string matches the regular expression pattern. Returns a corresponding match object if match found, else returns None if the string does not match the pattern.

All together:

import re

if __name__ == '__main__':
    string = "YourString123"
    pattern = re.compile("[A-Za-z0-9]+")

    # if found match (entire string matches pattern)
    if pattern.fullmatch(string) is not None:
        print("Found match: " + string)
    else:
        # if not found match
        print("No match")

Method 2

Just use str.isalnum()

>>> '123AbC'.isalnum()
True
>>> '1&A'.isalnum()
False

Referencing the docs:

Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one of the following returns Truec.isalpha()c.isdecimal()c.isdigit(), or c.isnumeric().

If you don’t want str.isdigit() or str.isnumeric() to be checked which may allow for decimal points in digits just use str.isnumeric() and str.isalpha():

>>> all(c.isnumeric() or c.isalpha() for c in '123AbC')
True
>>> all(c.isnumeric() or c.isalpha() for c in '1&A')
False

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read