如何在 Python 中创建 Number/Letter 间隔

How to make a Number/Letter interval in Python

所以... 我正在编写一个代码,使矩阵 table 然后 计算有多少 (大写字母,小写字母,数字,符号)

这是我试过的代码:

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)

所以输出应该是这样的:

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

问题出在间隔部分 Like ["A","Z"]

我不确定我是否 100% 理解您的需求,但我认为类似以下内容会适合:

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 "A" <= T[i][j] <= "Z":
            Nb_Maj = Nb_Maj + 1
        elif "a" <= T[i][j] <= "z" :
            Nb_Min = Nb_Min + 1
        elif 1 <= T[i][j] <= 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)

是的,这是完整的代码,如果有帮助的话:

from math import*

def Proc_saisie():
    X = -1
    while X < 1 or X > 20 :
        X = int(input("Donner un entier entre 5 et 20 : "))
    return X


def Proc_Remplir(P,X):
    T= [[] for i in range(P)]
    for i in range(P):
        for j in range(X):
            d = input("T["+str(i)+","+str(j)+"]=")
            T[i].append(d)
    return T

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)


#---------------------------

L = Proc_saisie()

C = Proc_saisie()
print("L =",L)
print("C =",C)
TAB = []

TAB = Proc_Remplir(L,C)


TAB = Proc_Affiche(TAB,L,C)

字符串有一些函数可以用来检查它们包含的内容

  • .isalpha() 对于字母
  • 是正确的
  • .isnumeric() 对于数字
  • 是正确的
  • .isalnum() 对于字母和数字都是如此
  • .isupper() 大写为真

因此你可以做类似的事情

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