python string.py 源码分析 二:capwords

时间:2021-07-25 00:00:42
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))

本语句非常精秒

先看join这个内置方法

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

capitalize() 首字母大写

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

以正常思维写法是

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

 

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