Python統計字母、中文、數字、空格等字符數
參考文章:https://blog.csdn.net/Guo_Apple/article/details/69390107
# 統計一行字符的不同字符個數
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(" "))) # 統計空格
print("該行字符有英文字符{0}個".format(count1)) # 計數統計,統計英文字符
print("該行字符有中文字符{0}個".format(count2)) # 計數統計,統計中文字符
print("該行字符有數字{0}個".format(count3)) # 計數統計,統計數字字符
print("該行字符有其他字符{0}個".format(len(str)-count1-count2-count3-str.count(" "))) # 統計其他字符
運行結果:
請輸入一行字符:中國特色社會主義進入了新時代,,,rhgi!@#$ eugi jvub us123456
該行字符有空格4個
該行字符有英文字符14個
該行字符有中文字符14個
該行字符有數字6個
該行字符有其他字符7個
總結
1.中文的Unicode編碼範圍0x4e00—0x9fa5
2.ord(x)函數,返回單字符x表示的Unicode編碼
3.str.count(x),返回x子串出現的次數