📜  Python程序来计算字符串中的字符数

📅  最后修改于: 2022-05-13 01:54:49.876000             🧑  作者: Mango

Python程序来计算字符串中的字符数

给定一个字符串。任务是返回字符串字符。

例子:

方法 #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))


输出

方法#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))
输出