Triste.own 发表于 2021-12-5 15:07:43

python字符统计

统计字符串中某类字符个数(字符分为大写字符、小写字符、数字字符、其他字符四类)。

suchocolate 发表于 2021-12-5 15:24:52

s = 'fishc123FISHC!@#'
result = {'uc': 0, 'lc': 0, 'num': 0, 'oth': 0}
for c in s:
    if c.isdigit():
      result['num'] += 1
    elif c.isalpha():
      if c.islower():
            result['lc'] += 1
      else:
            result['uc'] += 1
    else:
      result['oth'] += 1
print(result)

干虾皮 发表于 2021-12-5 17:51:48

def Statistics(Str):
    Str=list(Temp)
    print(Str)
    Length=len(Str)
    Lower_Case=0
    Capital=0
    Number=0
    Others=0
    while Length>0:
   
          if 'a'<=Str<='z':
            Lower_Case+=1
            Length-=1
          elif'A'<=Str<='Z':
            Capital+=1
            Length-=1
          elif'0'<=Str<='9':
            Number+=1
            Length-=1
          else:
             Others+=1
             Length-=1      
    print(Lower_Case)
    print(Capital)
    print(Number)
    print(Others)


Temp=input("请输入任意字符串")
Input=str(Temp)
Statistics(Input)

顺便问一下别人回答问题为啥都是代码形式,我把代码拷进来却是文本形式,求解答

suchocolate 发表于 2021-12-5 18:17:13

干虾皮 发表于 2021-12-5 17:51
def Statistics(Str):
    Str=list(Temp)
    print(Str)


干虾皮 发表于 2021-12-5 18:27:32

感谢suchocolate,明白了
页: [1]
查看完整版本: python字符统计