Bootstrap

Python 小练习 —— 统计字符串各类字符数量

需求

允许用户不断输入一个字符串。写一个函数负责统计该字符串中的字符、数字、空格、特殊字符的个数。

代码如下

# 统计字符、数字、特殊字符的个数
from typing import Tuple # 使用类型注释所需的库

# 定义函数,用到了类型注释。
def count_characters(msg: str) -> Tuple[int, int, int, int]:
    digit_count = 0 # 数字计数器
    alpha_count = 0 # 字母计数器
    space_count = 0 # 空格计数器
    special_count = 0 # 特殊字符计数器

    for s in msg:
        if s.isdigit():
            digit_count += 1
        elif s.isalpha():
            alpha_count += 1
        elif s.isspace():
            space_count += 1
        else:
            special_count += 1
    
    return digit_count, alpha_count, space_count, special_count

while True:
    msg = input("请输入一个串字符:")

    if not msg:
        print("请正确输入字符串!")
        continue

    if msg.lower() == "exit":
        print("退出程序")
        break

    digit_count, alpha_count, space_count, special_count = count_characters(msg)

    print(f"msg: {msg}")
    print(f"数字有{digit_count}个,字母有{alpha_count}个,空格有{space_count}个,其他字符有{special_count}")

涉及到的知识点:from...import...引入外部库、函数定义、变量定义、python3.5+类型注释、for循环、if判断、字符串的多种方法、while循环、continuebreak的区别、格式化字符串。

感谢浏览,一起学习!

;