当前位置:柔美女性网 >

绿色生活 >心理 >

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/lvse/xinli/eqozrr.html