python 輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。


一、參考解法:

s =input('請輸入字符串:')
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('統計字符串:',s)
print(dic)
print('------------顯示結果2---------------')  
for i in dic:
    print('%s='%i,dic[i])
print('------------顯示結果3---------------')  
for key,value in dic.items():
    print('%s='%key,value)

 

二、參考解法:

tmpStr = input('請輸入字符串:')
alphaNum=0
numbers=0
spaceNum=0
otherNum=0
for i in tmpStr:
    if i.isalpha():
        alphaNum +=1
    elif i.isnumeric():
        numbers +=1
    elif i.isspace():
        spaceNum +=1
    else:
        otherNum +=1
print('字母=%d'%alphaNum)
print('數字=%d'%numbers)
print('空格=%d'%spaceNum)
print('其他=%d'%otherNum)

 

三、參考解法:

InPut = input('請輸入字符串:')
letters  = [ ]
spaces = [ ]
digits   = [ ]
others = [ ] 
for i in iter(InPut):
    if i.isalpha():
        letters.append(i)
    elif i.isspace():
        spaces.append(i)
    elif i.isdigit():
        digits.append(i)
    else:
        others.append(i)
print('''
字母: {}, 個數: {}
空格: {}, 個數: {}
數字: {}, 個數: {}
其他: {}, 個數: {}'''\
.format(letters, len(letters), spaces, len(spaces), digits, len(digits),others, len(others)))

 

四、參考解法:

使用正則表達式 re.findall()

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)#漢字的Unicode編碼范圍
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)

 五、參考解法:

使用正則表達式 re.match()

import re
def splitFunc( ):
    tmpStr = input('請輸入字符串:')
    charNum = 0
    digNum = 0
    spaceNum = 0
    otherNum = 0
    for i in range(len(tmpStr)):
        if re.match('[a-zA-Z]',tmpStr[i]):
            charNum +=1
        elif re.match('\d',tmpStr[i]):
            digNum +=1
        elif re.match('\s',tmpStr[i]):
            spaceNum +=1
        else:
            otherNum +=1
    print('字符:',charNum)
    print('數字:',digNum)
    print('空格:',spaceNum)
    print('其他:',otherNum)
splitFunc() 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM