怎么用count(s,f)函数统计字符串中数字,大小写字母和其他字符的数目
我估计你是要自定义一个函数吧,我按这个思路给了个例子,s是字符串,f代表统计内容,0表示数字,1大写,2小写,3其它字符
az = 'abcdefghigklmnopqrstuvwxyz'
AZ = az.upper()
numbers = '0123456789'
def count(s, f=0):
if f==0:
nums = [n for n in s if n in numbers]
return len(nums)
elif f==1:
AZS = [az for az in s if az in AZ]
return len(AZS)
elif f==2:
azs = [a for a in s if a in az]
return len(azs)
else:
fhs = [fh for fh in s if (fh not in numbers and fh not in AZ and fh not in az)]
return len(fhs)
s = "12345ABCDEFGabcde~!@#$%^&*()"
print("数字个数:",count(s,0))
print("大写字母个数:",count(s,1))
print("小写字母个数:",count(s,2))
print("其它符号个数:",count(s,3))
“字符串中数字,大小写字母和其他字符”都算是字符串,
count(string, start_index, end_index)
count方法是用于寻找特定字符串所在的位置,而不是数学上计算总数的意思,
如果想计算一个字符串的长度,可以直接用length