Python: Count the number of occurrences of a character in a string

Hello everyone, my name is wangzirui32. This is my 50th original blog post. Please support me!
Today we will learn how to count the number of occurrences of a character in a string. In order for everyone to understand better, I will use an example to illustrate.
Start learning!


First, we need to use the count function to count. It can be used on strings or lists.
Example:

# 统计圆周率前100为出现0-9的次数

# 前100位 这里我们只留下前100位 去掉了3和小数点
pi = "1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"

for i in range(10):
	# count函数有一个参数 那就是要查找的字符
	number = pi.count(str(i))
	print("数字" + str(i) + "在圆周率前100位中出现过" + str(number) + "次!")

Run the code, output:

数字0在圆周率前100位中出现过8次!
数字1在圆周率前100位中出现过8次!
数字2在圆周率前100位中出现过12次!
数字3在圆周率前100位中出现过11次!
数字4在圆周率前100位中出现过10次!
数字5在圆周率前100位中出现过8次!
数字6在圆周率前100位中出现过9次!
数字7在圆周率前100位中出现过8次!
数字8在圆周率前100位中出现过12次!
数字9在圆周率前100位中出现过14次!

This completes a statistical example.


Well, today’s course is over, if you like, you can click to collect and pay attention, bye!

Guess you like

Origin blog.csdn.net/wangzirui32/article/details/114417405