python string.py 源码分析 二:capwords

def capwords(s, sep=None):
    """capwords(s [,sep]) -> string

    Split the argument into words using split, capitalize each
    word using capitalize, and join the capitalized words using
    join.  If the optional second argument sep is absent or None,
    runs of whitespace characters are replaced by a single space
    and leading and trailing whitespace are removed, otherwise
    sep is used to split and join the words.

    """
    return (sep or ' ').join(x.capitalize() for x in s.split(sep))

本语句很是精秒api

先看join这个内置方法app

",".join(["2","3","4"]) 结果为"2,3,4" spa

capitalize() 首字母大写code

split(sep)以sep为目标分割字符串blog

以正常思惟写法是rem

def capwords(s, sep=None):
    lt = []
    for x in s.split(sep):
        lt.append(x.capitalize())
    return (sep or ' ').join(lt)

 

能以一句这么精简的语句实现,真是太牛了。字符串

相关文章
相关标签/搜索