string模块1-capwords()

来源:互联网 发布:js object转string 编辑:程序博客网 时间:2024/06/03 11:18

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

原创粉丝点击