当前位置:首页python > 正文

python统计字符串中中英文、空格、数字、标点个数

作者:野牛程序员:2023-12-14 18:05:23python阅读 2789

使用Python统计字符串中中英文、空格、数字和标点的个数可以使用以下代码:

def count_characters(string):
    chinese_count = 0
    english_count = 0
    space_count = 0
    digit_count = 0
    punctuation_count = 0

    for char in string:
        if '\\u4e00' <= char <= '\\u9fff':
            chinese_count += 1
        elif char.isalpha():
            english_count += 1
        elif char.isspace():
            space_count += 1
        elif char.isdigit():
            digit_count += 1
        elif char in r"""!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~""":
            punctuation_count += 1

    return chinese_count, english_count, space_count, digit_count, punctuation_count

input_string = "你好,Hello 123! How are you today? 你好吗?"
result = count_characters(input_string)


//这段代码定义了一个函数count_characters,它接受一个字符串作为输入,并返回中文、英文、空格、数字和标点的个数。在给定的例子中,函数被调用来统计字符串"你好,Hello 123! How are you today? 你好吗?"中这些元素的个数。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击