Python程序来计算字符串中的字符数
给定一个字符串。任务是返回字符串字符。
例子:
Input : test_str = ‘geeksforgeeks !!$*** best 4 all Geeks 10-0’
Output : 25
Explanation : Only alphabets, when counted are 25
Input : test_str = ‘geeksforgeeks !!$*** best for all Geeks 10—0’
Output : 27
Explanation : Only alphabets, when counted are 27
方法 #1:使用 isalpha() + len()
在这种方法中,我们使用 isalpha() 检查每个字符是否为字母表,len() 用于获取字母表的长度以获取计数。
Python3
# Python3 code to demonstrate working of
# Alphabets Frequency in String
# Using isalpha() + len()
# initializing string
test_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'
# printing original string
print("The original string is : " + str(test_str))
# isalpha() to computation of Alphabets
res = len([ele for ele in test_str if ele.isalpha()])
# printing result
print("Count of Alphabets : " + str(res))
Python3
# Python3 code to demonstrate working of
# Alphabets Frequency in String
# Using ascii_uppercase() + ascii_lowercase() + len()
import string
# initializing string
test_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'
# printing original string
print("The original string is : " + str(test_str))
# ascii_lowercase and ascii_uppercase
# to check for Alphabets
res = len([ele for ele in test_str if ele in string.ascii_uppercase or ele in string.ascii_lowercase])
# printing result
print("Count of Alphabets : " + str(res))
The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0
Count of Alphabets : 27
方法#2:使用 ascii_uppercase() + ascii_lowercase() + len()
在此,我们使用内置函数执行将字母组合为大写和小写的任务,len() 返回频率。
蟒蛇3
# Python3 code to demonstrate working of
# Alphabets Frequency in String
# Using ascii_uppercase() + ascii_lowercase() + len()
import string
# initializing string
test_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'
# printing original string
print("The original string is : " + str(test_str))
# ascii_lowercase and ascii_uppercase
# to check for Alphabets
res = len([ele for ele in test_str if ele in string.ascii_uppercase or ele in string.ascii_lowercase])
# printing result
print("Count of Alphabets : " + str(res))
The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0
Count of Alphabets : 27