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)

 

能以一句這麼精簡的語句實現,真是太牛了。字符串

相關文章
相關標籤/搜索