python如何統(tǒng)計字符串中字符的個數
1.遍歷計數
遍歷字符串的每個字符,遍歷的時候加入判斷是否為字母的條件 isalpha,如果結果為 True 則計數器加1,否則進入下一個循環(huán)。
str_= "32Ss8nWn012"
str_count = 0
# 字符串本身就是迭代器
for s in str_:
if s.isalpha():
str_count += 1
# 輸出計數器
print(str_count)
5
2.匹配字母
2.1 字母表計數用string 模塊中的 ascii_lowercase 屬性,遍歷字母表,看看每個字母在我們的字符串中的數量,求和即可。然后還要注意:我們原始給定的字符串沒有規(guī)定大小寫,所以我們需要對原始字符串統(tǒng)一轉換成小寫字母(或者大寫字母)。
import string
str_ = "32Ss8nWn012"
str_count = 0
str_ = str_.lower()
# 遍歷ascii碼中的小寫英文字母
for i in string.ascii_lowercase:
# 內置函數count效率高
str_count += str_.count(i)
print(str_count)5
2.2 字母表計數這個方法與上一個方法都是匹配字母表,只不過這里用的是正則表達。
import re
str_ = "32Ss8nWn012"
# [a-zA-Z]是匹配內容,str_是待匹配的對象
str_ = re.findall('[a-zA-Z]',str_)
print(len(str_))
5
3.統(tǒng)計每個字符的個數
alist=['l','am','a','student']
#先將列表轉化為字符串
str=""
for i in alist:
str+=i
#統(tǒng)計無重復的字符
list=set(str)
print(list)
#利用count統(tǒng)計
li=[]
for j in list:
num=str.count(j)
#print(j)
print(num)
li.append(num)
print(li)
#讓元素的個數與元素一一對應
log3 = dict(zip(list,li))
print(log3){'e', 'u', 's', 'l', 'm', 'd', 'n', 't', 'a'}
1
1
1
1
1
1
1
2
2
[1, 1, 1, 1, 1, 1, 1, 2, 2]
{'e': 1, 'u': 1, 's': 1, 'l': 1, 'm': 1, 'd': 1, 'n': 1, 't': 2, 'a': 2}
附:Python統(tǒng)計英文、中文、數字、空格等字符數
Python統(tǒng)計字母、中文、數字、空格等字符數
# 統(tǒng)計一行字符的不同字符個數
str = input("請輸入一行字符:")
count1 = count2 = count3 = 0
for s in str:
if "a" <= s <= "z" or "A" <= s <= "Z":
count1 += 1 # 英文計數
elif 0x4e00 <= ord(s) <= 0x9fa5: # 中文的Unicode編碼范圍
count2 += 1 # 中文計數
elif 48 <= ord(s) and ord(s) <= 57:
count3 += 1 # 數字計數
print("該行字符有空格{0}個".format(str.count(" "))) # 統(tǒng)計空格
print("該行字符有英文字符{0}個".format(count1)) # 計數統(tǒng)計,統(tǒng)計英文字符
print("該行字符有中文字符{0}個".format(count2)) # 計數統(tǒng)計,統(tǒng)計中文字符
print("該行字符有數字{0}個".format(count3)) # 計數統(tǒng)計,統(tǒng)計數字字符
print("該行字符有其他字符{0}個".format(len(str)-count1-count2-count3-str.count(" "))) # 統(tǒng)計其他字符運行結果:
請輸入一行字符:哈哈哈哈哈哈哈哈哈哈哈哈哈哈,,,rhgi!@#$ eugi jvub us123456
該行字符有空格4個
該行字符有英文字符14個
該行字符有中文字符14個
該行字符有數字6個
該行字符有其他字符7個
小結
1.中文的Unicode編碼范圍0x4e00—0x9fa5
2.ord(x)函數,返回單字符x表示的Unicode編碼
3.str.count(x),返回x子串出現(xiàn)的次數
總結
到此這篇關于python統(tǒng)計字符串中字符個數的文章就介紹到這了,更多相關python統(tǒng)計字符個數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Django執(zhí)行python?manage.py?makemigrations報錯的解決方案分享
相信用過很多Django makemigrations的人都會遇到過makemigrations時會發(fā)生報錯,下面這篇文章主要給大家介紹了關于Django執(zhí)行python?manage.py?makemigrations報錯的解決方案,需要的朋友可以參考下2022-09-09

