Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am importing string and trying to check if text contains only "a-z", "A-Z", and "0-9".

But I get only input and it doesn't print success when I enter letters and digits

import string
text=input("Enter: ")
correct = string.ascii_letters + string.digits
if text in correct:
    print("Success")
like image 716
Elşən Kazım Avatar asked Jul 12 '19 18:07

Elşən Kazım


People also ask

What is the regular expression for identifiers with AZ and 0-9 }?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .

How do I check if a string has repeated characters?

If we want to know whether a given string has repeated characters, the simplest way is to use the existing method of finding first occurrence from the end of the string, e.g. lastIndexOf in java. In Python, the equivalence would be rfind method of string type that will look for the last occurrence of the substring.

How do you check if a string contains AZ?

To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise.

How do you regex only letters?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.


1 Answers

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")
like image 74
vs97 Avatar answered Nov 12 '22 00:11

vs97