Python函数第五节

2.定义一个func(name,callback=None),效果如下。
assert func("lilei") == "Lilei"
assert func("LILEI",callback=string.lower) == "lilei"
assert func("lilei",callback=string.upper) == "LILEI"

"""

import string
def func2(name, callback=None):
    if not isinstance(name, str):
        return 'not a name'
    if callback == None:
        return name.capitalize()
    return callback(name)

assert func2("lilei") == "Lilei"
assert func2("LILEI", callback=string.lower) == "lilei"
assert func2("lilei", callback=string.upper) == "LILEI"

# 对于string中的函数string.lower和string.upper是一个函数,通过回调函数callback,通过函数参数传递到其他代码执行的<pre name="code" class="python">4.定义一个func(*kargs),该函数效果如下返回最短的字符串。

assert func(222,1111,'xixi','hahahah') == "xixi"
assert func(7,'name','dasere') == 'name'
assert func(1,2,3,4) == None
"""


def func4(*kargs):
    list_filter = filter(lambda k: isinstance(k, str), kargs)
    if not list_filter:
        return None
    len_list = [len(i) for i in list_filter]
    min_len = min(len_list)
    return list_filter[len_list.index(min_len)]

#关于index的用法返回索引 str.index(self, begin, end)



展开阅读全文

没有更多推荐了,返回首页