Python counts the number of characters in a string

Python counts the number of characters in a string

1. Traverse count

Traverse each character of the string, and add the condition isalpha to judge whether it is a letter when traversing. If the result is True, the counter will increase by 1, otherwise enter the next cycle.

str_= "32Ss8nWn012"
str_count = 0
# 字符串本身就是迭代器
for s in str_:
    if s.isalpha():
        str_count += 1
# 输出计数器
print(str_count)
5

2. Match letters

2.1 Alphabet Count
Use the ascii_lowercase attribute in the string module to traverse the alphabet to see the number of each letter in our string, and then sum them up. Then also note: our original given string does not specify case, so we need to uniformly convert the original string into lowercase letters (or uppercase letters).

import string

str_ = "32Ss8nWn012"
str_count = 0
str_ = str_.lower()
# 遍历ascii码中的小写英文字母
for i in string.ascii_lowercase:
    # 内置函数count效率高
    str_count += str_.count(i)

print(str_count)
5

2.2 Alphabet counting
This method is matching alphabets with the previous method, except that regular expressions are used here.

import re

str_ = "32Ss8nWn012"
# [a-zA-Z]是匹配内容,str_是待匹配的对象
str_ = re.findall('[a-zA-Z]',str_)
print(len(str_))
5

3. Count the number of each character

alist=['l','am','a','student']
#先将列表转化为字符串
str=""
for i in alist:
    str+=i 
#统计无重复的字符    
list=set(str)
print(list)       
#利用count统计
li=[]
for j in list:
    num=str.count(j)
    #print(j)
    print(num)
    li.append(num)
print(li)
#让元素的个数与元素一一对应
log3 = dict(zip(list,li))
print(log3)
{
    
    'e', 'u', 's', 'l', 'm', 'd', 'n', 't', 'a'}
1
1
1
1
1
1
1
2
2
[1, 1, 1, 1, 1, 1, 1, 2, 2]
{
    
    'e': 1, 'u': 1, 's': 1, 'l': 1, 'm': 1, 'd': 1, 'n': 1, 't': 2, 'a': 2}

Guess you like

Origin blog.csdn.net/weixin_57038791/article/details/129225402