Search code examples
pythonmatrixintervals

How to make a Number/Letter interval in Python


So ... Am writing a code that makes a Matrix table then calculate how many ( uppercase Letter , Lowercase Letter , Numbers , Symbols )

That's the code i tried :

def Proc_Affiche(T,P,X):
    Nb_Maj = 0
    Nb_Min = 0
    Nb_chiffre = 0
    Nb_symbole = 0
    for i in range(P):
        for j in range(X):
            if T[i] in ["A","Z"]:
                Nb_Maj = Nb_Maj + 1
            elif T[i] in ["a","z"] :
                Nb_Min = Nb_Min + 1
            elif T[i] in range(1,9):
                Nb_chiffre = Nb_chiffre + 1
            else :
                Nb_symbole = Nb_symbole + 1
    print("Nb_Maj= ",Nb_Maj)
    print("Nb_Min= ",Nb_Min)
    print("Nb_chiffre= ",Nb_chiffre)
    print("Nb_symbole= ",Nb_symbole)

So the Output should be like that :

Nb_Maj=  ...
Nb_Min=  ...
Nb_chiffre=  ...
Nb_symbole=  ...

The Problem is on the part of intervals Like ["A","Z"]


Solution

  • Strings have some functions you can use to check what they contain

    • .isalpha() is true for letters
    • .isnumeric() is true for numbers
    • .isalnum() is true for letters and numbers
    • .isupper() is true for uppercase

    Thus you could do something like

    if T[i].isalpha():
        if T[i].isupper():
            Nb_Maj += 1
        else:
            Nb_Min += 1
    elif T[i].isnumeric():
        Nb_chiffre += 1
    else:
        Nb_symbole += 1