當前位置:柔美女性網 >

綠色生活 >心理 >

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

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

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

  • 文章版權屬於文章作者所有,轉載請註明 https://rmnxw.com/zh-hant/lvse/xinli/eqozrr.html