
python统计输入字符串中大写字母,小写字母,数字字符及其他字符个数 想问下应该怎样写
import re
def count_chars(string):
counts = {'uppercase': 0, 'lowercase': 0, 'digit': 0, 'other': 0}
for char in string:
if char.isupper():
counts['uppercase'] += 1
elif char.islower():
counts['lowercase'] += 1
elif char.isdigit():
counts['digit'] += 1
else:
counts['other'] += 1
return counts
def count_chars_regex(string):
pattern = r'[A-Z]|[a-z]|\d'
counts = {'uppercase': 0, 'lowercase': 0, 'digit': 0, 'other': 0}
for char in re.findall(pattern, string):
if char.isupper():
counts['uppercase'] += 1
elif char.islower():
counts['lowercase'] += 1
elif char.isdigit():
counts['digit'] += 1
else:
counts['other'] += 1
return counts
input_string = input('Enter a string: ')
# 使用字符串方法统计字符数量
counts = count_chars(input_string)
print('Using string methods: ', counts)
# 使用正则表达式模块re统计字符数量
counts_regex = count_chars_regex(input_string)
print('Using regex: ', counts_regex)