【基础入门题033】统计字符数

x33g5p2x  于2021-12-08 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(230)

【基础入门题】2021.11.29

给定一行字符串,分别统计出其中英文字母、数字、空格和其它字符的个数。

编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道   

————————————————

方法一:

def Character(Str):
    letters,digits,spaces,others = 0,0,0,0
    for s in Str:
        if 'a'<=s<='z' or 'A'<=s<='Z':
            letters += 1
        elif '0'<=s<='9':
            digits += 1
        elif s==' ':
            spaces += 1
        else:
            others += 1
    return letters,digits,spaces,others

print(Character('I am Hann Yang, my email is [hann@126.com].'))

方法二:与string库中的几个常量比较

def Character(Str):
    import string
    letters,digits,spaces,others = 0,0,0,0
    for s in Str:
        if s in string.ascii_letters:
            letters += 1
        elif s in string.digits:
            digits += 1
        elif s in string.whitespace:  #whitespaqce除了空格还包括'\t\n\r\x0b\x0c'
            spaces += 1
        else:
            others += 1
    return letters,digits,spaces,others

print(Character('I am Hann Yang, my email is [hann@126.com].'))

欢迎加入csdn社区! https://bbs.csdn.net/forums/PythonTogether

https://bbs.csdn.net/forums/PythonTogether

相关文章