python統計字符串中字母個數
給一個字符串,統計其中的數字、字母和其他類型字符的個數
例如:輸入“254h!%he”,輸出:數字=3,字母=3,其他=2
方法:
①首先用“str_count = 0”定義字母的字符初始個數為0
②接着遍歷字符串,判斷字符串內各字符的類型,並將字母個數累加
③最後用“print(‘字母 = %d’ %(str_count))”輸出字母個數結果即可。
數字初始個數
1
int_count = 0
字母初始個數
1
str_count = 0
其他字符初始個數
1
other_count = 0
輸入字符串
1
a = input(‘please input a strn’)
遍歷字符串
for i in a:
# 判斷是否為數字
if git():
int_count += 1
# 判斷是否為字母
elif num():
str_count += 1
# 判斷為其他字符
else:
other_count += 1
print(‘數字 = %d, 字母 = %d,其他 = %d’ %( int_count ,str_count,other_count))