首页 > 试题广场 >

编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、

[问答题]

编写函数,接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果。

#coding=utf-8
#https://www.nowcoder.com/questionTerminal/42e73e78bf334186bcf784e9cf7eb60e?mutiTagIds=573&orderByHotValue=1&questionTypes=000010
def count_all(str):
    res = [0,0,0,0]
    for i in str:
        if i.islower():
            res[0] += 1
        elif i.isupper():
            res[1] += 1
        elif i.isdigit():
            res[2] += 1
        else:
            res[3] += 1
    return ('A-Z',res[1]),('a-z',res[0]),('0-9',res[2]),('others',res[3])
    
print count_all('Acasda1234214___;')

发表于 2018-05-15 22:55:04 回复(0)

这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。

def demo(v):
    capital = little = digit = other =0
    for i in v:
        if 'A'<=i<='Z':
            capital+=1
        elif 'a'<=i<='z':
            little+=1
        elif '0'<=i<='9':
            digit+=1
        else:
            other+=1
    return (capital,little,digit,other)
x = 'capital = little = digit = other =0'
print(demo(x))

发表于 2017-12-28 15:46:44 回复(0)