统计字符串中字母个数的方法有多种,以下是使用纯Python和第三方库的两种常见方法:
使用纯Python
def count_letters(string):
count = 0
for char in string:
if char.isalpha():
count += 1
return count
string = "Hello, World! 123"
print(count_letters(string)) 输出:10
使用第三方库
from collections import Counter
def count_letters_with_collections(string):
return Counter(c for c in string if c.isalpha())
string = "Hello, World! 123"
print(count_letters_with_collections(string)) 输出:Counter({'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1})
以上两种方法都可以统计字符串中的字母个数。第一种方法使用纯Python实现,第二种方法利用了`collections`库中的`Counter`类,使得代码更简洁高效。