Python 统计字符串中的字符类型数量

# 求字符串长度的函数
def strlen(s):
    return s + '的长度是 : ' + str(len(s))
    # return len(s)
    # len()方法返回的是数字,在拼接字符串的时候需要,转换为string(用str()方法)


# 计算字符串中数字,字母、空格和其他的个数
def strnum(s):
    digitNum = 0
    spaceNum = 0
    alphaNum = 0
    otherNum = 0
    for i in s:
        if i.isdigit():
            digitNum = digitNum + 1
        elif i.isspace():
            spaceNum = spaceNum + 1
        elif i.isalpha():
            alphaNum += 1
        else:
            otherNum += 1
    # 返回一个字典的方法
    # return {'数字':digitNum, '空格':spaceNum, '字母':alphaNum, '其他':otherNum}
    # 返回一个元祖
    return (digitNum,spaceNum,alphaNum,otherNum)


s1 = input("请输入一个字符串:")
print(strlen(s1))
print(strnum(s1))

# 测试用例
# 请输入一个字符串:fegsa;'j hglig
# fegsa;'j hglig的长度是 : 14
# (0, 1, 11, 2)

# 重点是记住,判断字母,空格, 数字的函数
# elif 不是 else if
# 没有(), 有:
# 函数是 def strnum(s): 不是 def strnum(string s): 不是 def strnum :

猜你喜欢

转载自blog.csdn.net/ai_shuyingzhixia/article/details/80769073