美文网首页
python -21-用字典存储字符串不同字符的个数

python -21-用字典存储字符串不同字符的个数

作者: hsiaojun | 来源:发表于2018-04-19 01:29 被阅读0次

    要求统计输入的字符串中不同字符的个数,使用字典存储,并打印出来

    while True:
        # 获取键盘输入
        str_input = input("请任意输入一个字符串(长1-31):")
        # 测试长度:
        if len(str_input)<1 or len(str_input)>31:
            print("长度超出限制,请重新输入")
            continue
    
        # 统计字符个数的字典
        count_dict = {}
        for c in str_input:
            # 如果有,则将其原来的值+1   #难以理解,多加注意
            if c in count_dict:
                count_dict[c] += 1
            # 如果没有,则新增加这个键值对值设为1
            else:
                 count_dict[c] = 1
        # 打印其长度并逆序打印字符串
        print("您输入的字符串%s\n"%str_input,\
                "长度:%d\n"%len(str_input),\
                "逆序后为:%s\n"%str_input[::-1],\
                "字符统计结果:",count_dict
             )
    

    相关文章

      网友评论

          本文标题:python -21-用字典存储字符串不同字符的个数

          本文链接:https://www.haomeiwen.com/subject/bcdikftx.html