string模块1-capwords()

“The following functions are available to operate on string and Unicode objects.They are not available as string methods.”

以上这句话是python在线文档中对string模块函数的说明;第一句说以下函数可用来操作字符串或Unicode对象,这个好理解。第二句话说,他们不可用做模块的方法,我理解的这些函数就是模块的方法呀,说的很奇怪。

string.capwords(s[,sep])

以上是这个capwords()的使用形式,[,sep]是个可选项。

这个函数首先会把参数(这个s一般是个字符串)用str.split() 分割成一个个单词,再用str.capitalize()函数把每个单词的首字母大写,最后用str.join()函数将单词组合起来,如果第二个可选参数“sep”为空或为none,多个空格会被一个空格代替,字符串开头和结尾的空格将会被移除,另外,sep 这个参数是用来分割和组合字符串的,以下是例子。

import string

s = 'The quick brown fox jumped over the lazy dog.'

print s

print string.capwords(s)

print string.capwords(s,None)

print string.capwords('abcabcabc','a')

结果:

The quick brown fox jumped over the lazy dog.

The Quick Brown Fox Jumped Over The Lazy Dog.

The Quick Brown Fox Jumped Over The Lazy Dog.

aBcaBcaBc


函数定义:

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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值