靚麗時尚館

位置:首頁 > 健康生活 > 心理

python如何統計數字和小寫字母

心理7.7K
python如何統計數字和小寫字母

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))