Python 字符串方法详解

在编程中,几乎90% 以上的代码都是关于整数或字符串操作,所以与整数一样,Python
的字符串实现也使用了许多拿优化技术,使得字符串的性能达到极致。与 C++ 标准库(STL)中的 std::string 不同,python
字符串集合了许多字符串相关的算法,以方法成员的方式提供接口,使用起来非常方便。 字符串方法大约有几十个,这些方法可以分为如下几类(根据 manuals 整理):

类型

方法

注解

填充

center(width[, fillchar]) ,
ljust(width[, fillchar]),
rjust(width[, fillchar]),
zfill(width),
expandtabs([tabsize])

l         fillchar 参数指定了用以填充的字符,默认为空格
l         顾名思义,zfill()即是以字符0进行填充,在输出数值时比较常用
l         expandtabs()的tabsize 参数默认为8。它的功能是把字符串中的制表符(tab)转换为适当数量的空格。

删减

strip([chars]),
lstrip([chars]),
rstrip([chars])

*strip()函数族用以去除字符串两端的空白符,空白符由string.whitespace常量定义。

变形

lower(),
upper(),
capitalize(),
swapcase(),
title()

title()函数是比较特别的,它的功能是将每一个单词的首字母大写,并将单词中的非首字母转换为小写(英文文章的标题通常是这种格式)。
>>> ‘hello wORld!’.title()
‘Hello World!’
因为title() 函数并不去除字符串两端的空白符也不会把连续的空白符替换为一个空格,所以建议使用string 模块中的capwords(s)函数,它能够去除两端的空白符,再将连续的空白符用一个空格代替。
>>> ‘ hello   world!’.title()
‘ Hello   World!’
>>> string.capwords(’ hello   world!’)
‘Hello World!’
 

分切

partition(sep),
rpartition(sep),
splitlines([keepends]),
split([sep [,maxsplit]]),
rsplit([sep[,maxsplit]])

l         *partition()
函数族是2.5版本新增的方法。它接受一个字符串参数,并返回一个3个元素的 tuple 对象。如果sep没出现在母串中,返回值是 (sep,
‘’, ‘’);否则,返回值的第一个元素是 sep 左端的部分,第二个元素是 sep 自身,第三个元素是 sep 右端的部分。
l         参数 maxsplit 是分切的次数,即最大的分切次数,所以返回值最多有 maxsplit+1 个元素。
l         s.split() 和 s.split(‘ ‘)的返回值不尽相同
>>> ‘ hello   world!’.split()
['hello', 'world!']
>>> ‘ hello   world!’.split(’ ‘)
['', '', 'hello', '', '', 'world!']

生差异的原因在于当忽略 sep 参数或sep参数为 None 时与明确给 sep 赋予字符串值时 split()
采用两种不同的算法。对于前者,split()
先去除字符串两端的空白符,然后以任意长度的空白符串作为界定符分切字符串(即连续的空白符串被当作单一的空白符看待);对于后者则认为两个连续的
sep 之间存在一个空字符串。因此对于空字符串(或空白符串),它们的返回值也是不同的:
>>> ”.split()
[]
>>> ”.split(’ ‘)
['']

连接

join(seq)

join() 函数的高效率(相对于循环相加而言),使它成为最值得关注的字符串方法之一。它的功用是将可迭代的字符串序列连接成一条长字符串,如:
>>> conf = {’host’:'127.0.0.1′,
…     ‘db’:’spam’,
…     ‘user’:’sa’,
…     ‘passwd’:'eggs’}
>>> ‘;’.join("%s=%s"%(k, v) for k, v in conf.iteritems())
‘passswd=eggs;db=spam;user=sa;host=127.0.0.1′

判定

isalnum(),
isalpha(),
isdigit(),
islower(),
isupper(),
isspace(),
istitle(),
startswith(prefix[, start[, end]]),
endswith(suffix[,start[, end]])

这些函数都比较简单,顾名知义。需要注意的是*with()函数族可以接受可选的 start, end 参数,善加利用,可以优化性能。
另,自 Py2.5 版本起,*with() 函数族的 prefix 参数可以接受 tuple 类型的实参,当实参中的某人元素能够匹配,即返回 True。

查找

count( sub[, start[, end]]),
find( sub[, start[, end]]),
index( sub[, start[, end]]),
rfind( sub[, start[,end]]),
rindex( sub[, start[, end]])

find()函数族找不到时返回-1,index()函数族则抛出ValueError异常
另,也可以用 in 和 not in 操作符来判断字符串中是否存在某个模板。

替换

replace(old, new[,count]),
translate(table[,deletechars])

l         replace()函数的 count 参数用以指定最大替换次数
l         translate() 的参数 table 可以由 string.maketrans(frm, to) 生成
l         translate() 对 unicode 对象的支持并不完备,建议不要使用。

编码

encode([encoding[,errors]]),
decode([encoding[,errors]])


是一对互逆操作的方法,用以编码和解码字符串。因为str是平台相关的,它使用的内码依赖于操作系统环境,而unicode是平台无关的,是Python
内部的字符串存储方式。unicode可以通过编码(encode)成为特定编码的str,而str也可以通过解码(decode)成为unicode。

本文最初发表于赖勇浩(恋花蝶)的博客(http://blog.csdn.net/lanphaday),如蒙转载,敬请保留全文完整,切勿去除本声明和作者信息。

      

 

附注:

1)C++ 中可以通过 boost.string_algo 库来获得同样方便的字符串处理能力。

2)这些字符串方法在 python1.6 版本才开始提供,如果你使用的python版本非常老,可能需要使用string模块来获得这些方便的算法。

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. Python 多线程 XML RPC的实现
  2. Python 3.1.1 RC发布
  3. 开始Python — Dictionary
  4. 在apache上面部署django应用
  5. Python Imaging Library (PIL)
  6. Core Python Programming(1) - Basic
  7. python国际化(i18n)和中英文切换

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu