首页 > 试题广场 >

3[问答] 编写函数,接收一个字符串,分别统计大写字...

[问答题]
 编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果。
def count(string):
    import re
    num_Calpha=len(re.sub('[^A-Z]','',string))     num_Lalpha=len(re.sub('[^a-z]','',string)) 
    num_digit=len(re.sub('[^0-9]','',string))  
    num_other=len(re.sub('[A-Za-z0-9]','',string))  
    return num_Calpha,num_Lalpha,num_digit,num_other  

编辑于 2018-09-19 15:43:39 回复(0)
def demo(n):
   Calpha =Lalpha= digit = other =0
    for i in n:
        if 'A'<=i<='Z':
            Calpha+=1
        elif 'a'<=i<='z':
          Lalpha+=1
        elif '0'<=i<='9':
            digit+=1
        else:
            other+=1
    return (capital,Lalpha,digit,other)
x = 'Calpha =Lalpha = digit = other =0'
print(demo(x))

发表于 2019-07-09 18:51:14 回复(0)
题目是统计字母,不是单词
import re
def handle(text):
    diglet = len(re.findall("[A-Z]", text))
    lower = len(re.findall("[a-z]", text))
    num = len(re.findall("[0-9]", text))
    other = len(re.findall("[^A-Za-z0-9]", text))
    return (diglet, lower, num, other)


发表于 2020-06-04 01:03:41 回复(0)
发表于 2020-05-20 22:28:31 回复(0)
可以参照评论中的re模块findall逻辑
def main():
    list=[]
    str_input=input('输入字符串:')
    for i in str_input:;
        if i isupper():
            list[0]+=1
        elif i islower():    list[1]+=1
        elif i isnumeric():    list[2]+=1
        else:
             list[3]+=1
     tup=tuple(list)
     print(tup) if __name__=='__main__':
    main()

编辑于 2020-02-22 21:43:12 回复(0)
import re
statistical_list=[]
re_str='hjaasUI1***'

AZ = re.findall(r'[A-Z]',re_str)
statistical_list.append(len(AZ))

az = re.findall(r'[a-z]',re_str)
statistical_list.append(len(az))

zj=re.findall(r"\d",re_str)
statistical_list.append(len(zj))

other_num=re.findall(r"\W",re_str)
statistical_list.append(len(other_num))

statistical_tu=tuple(statistical_list)
print(statistical_tu)

发表于 2019-11-04 16:21:12 回复(0)
# MySam123$2@ import re def func(mystr):  pass    big = len(re.findall(r'[A-Z]',mystr))
    ***all = len(re.findall(r'[a-z]', mystr))
    num = len(re.findall(r'[0-9]', mystr))
    ot = len(re.findall(r'[^a-zA-Z0-9]', mystr))  print big, ***all, num, ot  return big, ***all, num, ot
mystr = raw_input("请输入一串字符串:")
func(mystr)


发表于 2019-05-21 22:00:32 回复(0)

re.finall("\d", string),返回包含所有数字的列表。用tuple(list)转化为元组,其他同理。

发表于 2019-03-17 13:44:55 回复(0)