Home  >  Article  >  Backend Development  >  How to count the number of letters in a string in Python?

How to count the number of letters in a string in Python?

烟雨青岚
烟雨青岚Original
2020-07-06 10:53:3253601browse

Method: First use "str_count = 0" to define the initial number of characters of letters as 0; then traverse the string, determine the type of each character in the string, and accumulate the number of letters; finally use "print ('letters = %d' %(str_count))" just output the number of letters.

How to count the number of letters in a string in Python?

Python counts the number of letters in a string

Given a string, count the numbers in it , letters and other types of characters;

For example: input "254h!%he", output: numbers = 3, letters = 3, others = 2

Method:

① First use "str_count = 0" to define the initial number of characters of letters as 0

② Then traverse the string and determine the type of each character in the string. And accumulate the number of letters;

③Finally use "print('letters = %d' %(str_count))" to output the result of the number of letters.

Initial number of digits

int_count = 0

Initial number of letters

str_count = 0

Initial number of other characters

other_count = 0

Input string

a = input(‘please input a str\n’)

Traversing strings

for i in a:
# 判断是否为数字
if i.isdigit():
int_count += 1
# 判断是否为字母
elif i.isalnum():
str_count += 1
# 判断为其他字符
else:
other_count += 1
print(‘数字 = %d, 字母 = %d,其他 = %d’ %( int_count ,str_count,other_count))

Recommended tutorial: "python tutorial"

The above is the detailed content of How to count the number of letters in a string in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn