GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — Python 练习实例17 | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
Python 基础教程
Python 基础教程 Python 简介 Python 环境搭建 Python 中文编码 Python VS Code Python 基础语法 Python 变量类型 Python 运算符 Python 条件语句 Python 循环语句 Python While 循环语句 Python for 循环语句 Python 循环嵌套 Python break 语句 Python continue 语句 Python pass 语句 Python Number(数字) Python 字符串 Python 列表(List) Python 元组 Python 字典(Dictionary) Python 日期和时间 Python 函数 Python 模块 Python 文件I/O Python File 方法 Python 异常处理 Python OS 文件/目录方法 Python 内置函数

Python 高级教程

Python 面向对象 Python 正则表达式 Python CGI 编程 Python MySQL Python 网络编程 Python SMTP Python 多线程 Python XML 解析 Python GUI 编程(Tkinter) Python2.x 与 3​​.x 版本区别 Python IDE Python JSON Python AI 绘画 Python 100例 Python 测验
Python 练习实例16
Python 练习实例18

Python 练习实例17

Python 100例 Python 100例

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

程序分析:利用 while 或 for 语句,条件为输入的字符不为 '\n'。

实例(Python2.x) - 使用 while 循环

#!/usr/bin/python # -*- coding: UTF-8 -*- import string s = raw_input('请输入一个字符串:\n') letters = 0 space = 0 digit = 0 others = 0 i=0 while i < len(s): c = s[i] i += 1 if c.isalpha(): letters += 1 elif c.isspace(): space += 1 elif c.isdigit(): digit += 1 else: others += 1 print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)

实例(Python3.x) - 使用 for 循环

#!/usr/bin/python3 import string s = input('请输入一个字符串:\n') letters = 0 space = 0 digit = 0 others = 0 for c in s: if c.isalpha(): letters += 1 elif c.isspace(): space += 1 elif c.isdigit(): digit += 1 else: others += 1 print ('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))

以上实例输出结果为:

请输入一个字符串:
123runoobc  kdf235*(dfl
char = 13,space = 2,digit = 6,others = 2

Python 100例 Python 100例

AI 思考中...
Python 练习实例16
Python 练习实例18

9 篇笔记 写笔记

  1. #0

       健健

      459***[email protected]

    18

    Python3 下参考方案(可使用中文作为变量):

    #!/usr/bin/python3
    
    a = input('请输入一串字符:')
    英文 = 0
    空格= 0
    数字= 0
    其他= 0
    for i in a:
        if i.isalpha():
            英文 += 1
        elif i.isspace():
            空格 += 1
        elif i.isnumeric():
            数字 += 1
        else:
            其他 += 1
    print('英文 = %s,空格 = %s,数字 = %s,其他 = %s' % (英文,空格,数字,其他))
    
    健健

       健健

      459***[email protected]

    10年前 (2017-04-22)
  2. #0

       等一个人

      252***[email protected]

    8

    Python3 下测试:

    #!/usr/bin/env python3
    
    InPut = input('输入任意字符:')
    letters = []
    spaces = []
    digits = []
    others = []
    for i in iter(InPut):
        if i.isalpha() == True:
            letters.append(i)
        elif i.isspace() == True:
            spaces.append(i)
        elif i.isdigit() == True:
            digits.append(i)
        else:
            others.append(i)
    print('''
    字母: {}, 个数: {};
    空字符: {}, 个数: {};
    数字: {}, 个数: {};
    其他: {}, 个数: {}'''.format(letters, len(letters), spaces, len(spaces), digits, len(digits), others, len(others)))
    
    等一个人

       等一个人

      252***[email protected]

    10年前 (2017-04-28)
  3. #0

       大愚

      923***[email protected]

    4

    使用正则表达式来计算(无法统计中文,要统计中文可以参考下面的例子):

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import re
    
    def splitFunc():
        tmpStr = raw_input("输入字符串:")
        charNum  = 0
        digNum = 0
        spaceNum=0
        otherNum =0
        for i in range(len(tmpStr)):
            if re.match('\d',tmpStr[i]):
                digNum +=1
            elif re.match('[a-zA-Z]',tmpStr[i]):
                charNum +=1
            elif re.match('\s',tmpStr[i]):
                spaceNum +=1
            else:
                otherNum +=1
        print "字符:",charNum
        print "数字:",digNum
        print "空格:",spaceNum
        print "其他:",otherNum
    splitFunc()
    
    大愚

       大愚

      923***[email protected]

    10年前 (2017-05-10)
  4. #0

       小雨济苍生

      27d***163.com

    5

    参考方法:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import  re
    str=raw_input('请输入一串字符:')
    
    r1=re.compile('[a-zA-Z]')
    r2=re.compile('[0-9]')
    print '英文字母的个数为: %d' %len(re.findall(r1,str))
    print '数字的个数为: %d' %len(re.findall(r2,str))
    print '空格的个数为: %d' %len(re.findall(' ',str))
    print '其他字符的个数为: %d' %(len(str)-len(re.findall(r1,str))-len(re.findall(r2,str))-len(re.findall(' ',str)))
    
    小雨济苍生

       小雨济苍生

      27d***163.com

    10年前 (2017-05-25)
  5. #0

       Almighty

      132***[email protected]

    13

    python3 参考方法:

    #!/usr/bin/env python3
    
    a = str(input("输入一行字符:"))
    count1 = 0  #统计英文字母个数
    count2 = 0  #统计数字个数
    count3 = 0  #统计空格个数
    count4 = 0  #统计其他字符
    for i in range(len(a)):   #利用字符在ASCII码中的位置逐个统计
        if("0" <= a[i] <= "9"):
            count2 += 1
        elif("A" <= a[i] <= "Z" or "a" <= a[i] <= "z"):
            count1 += 1
        elif(a[i] == " "):
            count3 += 1
    count4 = len(a) - count1 - count2 - count3
    print("英文字母有%d个\n数字有%d个\n空格有%d个\n其他字符有%d个\n"%(count1,count2,count3,count4))
    
    Almighty

       Almighty

      132***[email protected]

    10年前 (2017-05-31)
  6. #0

       Flytiger

      841***[email protected]

    0

    使用匿名函数 lambda:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    s = raw_input('请输入一个字符串:\n')
    print "开始统计..."
    list = [0, 0, 0, 0]
    temp = [lambda i : 1 if (i.isalpha()) else 0, lambda i : 1 if (i.isspace()) else 0, lambda i : 1 if (i.isdigit()) else 0]
    for i in s:
        list[0] += temp[0](i)    # 字母
        list[1] += temp[1](i)    # 空格
        list[2] += temp[2](i)    # 数字
        list[3] = len(s) - list[0] - list[1] - list[2]  # 特殊字符
    
    print list
    
    Flytiger

       Flytiger

      841***[email protected]

    10年前 (2017-06-13)
  7. #0

       chengxuyuan

      hdw***[email protected]

    0

    用 decode() 解码可以统计中文个数,utf-8 下一个中文占 3 位。

    # encoding:utf-8
    
    import re
    
    '''因为中文字符占用长度不是1,用len()方法无法识别中文个数
    '''
    #答案方法
    str = raw_input('请输入一行字符:')
    str = str.decode('utf-8') # 解码成 unicode 类型,在 unicode 类型中,汉字占一位
    word = 0
    num = 0
    space = 0
    other = 0
    for i in str:
        if re.match(r'\d', i):
            num += 1
        elif re.match(r'\w', i) and not re.match(r'\d', i):
            word += 1
        elif re.match(' ', i):
            space += 1
        else:
            other += 1
    print '字母个数为:', word
    print '数字个数为:', num
    print '空格个数为:', space
    print '其他字符个数:', other
    chengxuyuan

       chengxuyuan

      hdw***[email protected]

    9年前 (2017-08-18)
  8. #0

       tlf

      694***[email protected]

    6

    Python3 测试,可以统计中文:

    #!/usr/bin/python3
    
    #输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
    #不能有效区分汉字。。。好像没有特定识别汉字的通用表达\s这样的#4E00~9FFFh 是中文的数字区域
    import re
    s = input('输入一串字符:')
    char = re.findall(r'[a-zA-Z]',s)
    num = re.findall(r'[0-9]',s)
    blank = re.findall(r' ',s)
    chi = re.findall(r'[\u4E00-\u9FFF]',s)
    other = len(s)-len(char)-len(num)-len(blank)-len(chi)
    print("字母:", len(char),"\n数字:", len(num),"\n空格:",len(blank),"\n中文:",len(chi),"\n其他:",other)
    
    tlf

       tlf

      694***[email protected]

    9年前 (2017-08-25)
  9. #0

       zhangsan

      10k***[email protected]

    2

    参考方法:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    s ='12 3 45 & *?.;hGGK L67890'
    
    dic = {'letter':0,'integer':0,'space':0,'other':0}
    for i in s:
        if i>'a' and i<'z' or i>'A' and i<'Z':
            dic['letter'] += 1
        elif i in '0123456789':
            dic['integer'] += 1
        elif i == ' ':
            dic['space'] += 1
        else:
            dic['other'] += 1
    print dic
    zhangsan

       zhangsan

      10k***[email protected]

    9年前 (2017-09-26)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.