简单函数练习

1、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def func(s):
    dic = {
        'num':0,
        'alpha':0,
        'space':0,
        'other':0
    }
    for i in s:   #item  项
        if i.isdigit():
            dic['num'] += 1
        elif i.isalpha():
            dic['alpha'] +=1
        elif i.isspace():
            dic['space'] += 1
        else:
            dic['other'] += 1
    return dic

 s = 'hello name:asomebody password:123456'
 ret = func(s)
 print(ret)
2、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def func2(o):
    length = len(o)
    if length > 5:
        return True
    else:
        return False

 ret = func2([1,2,3])
 print(ret)
    if ret:
     print('大于5')
else:
    print("小于等于5")
3、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def func3(l):
    if len(l) > 2:
        return l[0:2]
    else:
        return l

l = [1,2,3,4,5,6]
l2 = func3(l)
print(l2)
4、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def func4(o):
    # newl = o[1::2]
    # return newl
    return o[1::2]

func4([1,2,3,4,5,6])

 

posted @ 2017-07-26 19:10  NeitherCandidate  阅读(217)  评论(0编辑  收藏  举报