Python classic 100 questions: counting the number of characters

Question: Enter a line of characters and count the number of English letters, spaces, numbers and other characters in it.

method one:

str_input = input("请输入一行字符:")
count_letter, count_space, count_digits, count_other = 0, 0, 0, 0
for char in str_input:
    if char.isalpha():
        count_letter += 1
    elif char.isspace():
        count_space += 1
    elif char.isdigit():
        count_digits += 1
    else:
        count_other += 1
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

Idea: Use a for loop to traverse each character in the string, determine whether it belongs to English letters, spaces, numbers, or other characters, and record the corresponding number. Finally output the result.

Advantages: Simple and easy to understand, less code.

Disadvantages: There are many if-elif statements and the code is less readable.

Method Two:

str_input = input("请输入一行字符:")
count_letter = sum(1 for char in str_input if char.isalpha())
count_space = sum(1 for char in str_input if char.isspace())
count_digits = sum(1 for char in str_input if char.isdigit())
count_other = len(str_input) - count_letter - count_space - count_digits
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

Idea: Use generator expressions and sum functions to integrate the process of determining which category a character belongs to into one line of code to simplify the code.

Advantages: less code and better readability.

Disadvantages: The generator expression is nested in the sum function, which is slightly less readable.

Method three:

from collections import Counter

str_input = input("请输入一行字符:")
count_dict = Counter(str_input)
count_letter = count_dict.get("{}".format(chr(10))) - 1    # 减去回车符的个数
count_space = count_dict.get(" ")
count_digits = sum(1 for key in count_dict if key.isdigit())
count_other = len(str_input) - count_letter - count_space - count_digits
print("英文字母个数为:", count_letter)
print("空格个数为:", count_space)
print("数字个数为:", count_digits)
print("其他字符个数为:", count_other)

Idea: Use the Counter counter in the Python standard library to record all characters in the string and their occurrence times, and then obtain the number of English letters, spaces, numbers and other characters through the get method of the dictionary.

Advantages: The code is concise and readable.

Disadvantages: You need to import the collections library. If you are not familiar with this library, it may be difficult to understand.

To sum up, all three methods can count the number of English letters, spaces, numbers and other characters. Which method to choose depends mainly on the actual situation of the project and personal preferences.

Guess you like

Origin blog.csdn.net/yechuanhui/article/details/132900123