Python字符串大小写转换及字符统计

以下是使用Python实现字符串大小写转换和字符统计的代码示例:

def count_character_types(input_str):
    uppercase_count = 0
    lowercase_count = 0
    digit_count = 0
    other_count = 0

    for char in input_str:
        if char.isupper():
            lowercase_count += 1
            char = char.lower()
        elif char.islower():
            uppercase_count += 1
            char = char.upper()
        elif char.isdigit():
            digit_count += 1
        else:
            other_count += 1

    return {
        'uppercase_count': uppercase_count,
        'lowercase_count': lowercase_count,
        'digit_count': digit_count,
        'other_count': other_count
    }

input_str = input('请输入字符串:')
result = count_character_types(input_str)
print('大写字母数量:', result['uppercase_count'])
print('小写字母数量:', result['lowercase_count'])
print('数字数量:', result['digit_count'])
print('其他字符数量:', result['other_count'])

这段代码首先定义了一个名为count_character_types的函数,该函数接受一个字符串作为输入,并返回一个字典,其中包含大写字母、小写字母、数字和其他字符的数量。

代码主体部分首先提示用户输入一个字符串,然后调用count_character_types函数对输入的字符串进行处理。最后,代码打印出统计结果,包括大写字母数量、小写字母数量、数字数量和其他字符数量。

需要注意的是: 这段代码只是一个简单的实现,可能不适用于非ASCII字符或特殊情况。如果有特殊需求,请根据实际情况修改代码。

Python字符串大小写转换及字符统计

原文地址: https://www.cveoy.top/t/topic/Tty 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录