求python大神帮忙,在python下,输入一串字符串,输出元素个数。急!!!!!!!!!!!!!!

2024-12-26 10:57:21
推荐回答(3个)
回答1:

# 稍作改造
data="asdfasdfasdffrist'~!$123@df#456asgh'endasdfasdfasdf"
counter = [0, 0, 0, 0]
for ch in data:
    if ch.isupper():
        counter[0] += 1
    elif ch.islower():
        counter[1] += 1
    elif ch.isdigit():
        counter[2] += 1
    else:
        counter[3] += 1
print counter

# 再改:

UPPER, LOWER, DIGIT, OTHER = range(4)

def chtype(ch):
    if ch.isupper():
        return UPPER
    elif ch.islower():
        return LOWER
    elif ch.isdigit():
        return DIGIT
    else:
        return OTHER

def counter(data):
    _counter = [0, 0, 0, 0]
    for ch in data:
        _counter[chtype(ch)] += 1
    return _counter


data="asdfasdfasdffrist'~!$123@df#456asgh'endasdfasdfasdf"
print counter(data)

回答2:

抄一段以前的回答:

import re
data="asdfasdfasdffrist'~!$123@df#456asgh'endasdfasdfasdf"
print len(''.join(re.findall(r'[^0-9a-zA-Z]*',data)))#其他
print len(''.join(re.findall(r'\d*',data)))#数字
print len(''.join(re.findall(r'[A-Z]*',data)))#大写
print len(''.join(re.findall(r'[a-z]*',data)))#小写

回答3:

mystr = 'A123#$&BCDqweqweq'

def countstr(s):

count = [0, 0, 0, 0]
for c in s:

count[0] += c.isupper()
count[1] += c.islower()
count[2] += c.isdigit()

count[3] = len(s) - count[0] - count[1] - count[2]
return count

count = countstr(mystr)

print 'upper:', count[0], 'lower:', count[1], 'int:', count[2], 'other:', count[3]