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

Python 基础教程
(追記) (追記ここまで)

Python 练习实例17

Python 100例 Python 100例

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

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

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

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

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

#!/usr/bin/python3importstrings = input('请输入一个字符串:\n')letters = 0space = 0digit = 0others = 0forcins: ifc.isalpha(): letters += 1elifc.isspace(): space += 1elifc.isdigit(): digit += 1else: others += 1print('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 思考中...

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]

    9年前 (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]

    9年前 (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]

    9年前 (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

    9年前 (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

    132***[email protected]

    9年前 (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

    841***[email protected]

    9年前 (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

    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

    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

    10k***[email protected]

    9年前 (2017年09月26日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /