Python 字符串

(0 comments)

string - Common string operations

http://www.python.org/doc/2.4/lib/module-string.html

赋值语法

% 方法处理字符串是最节约资源的。

print "%d is %s old years" % (name, age)

表示大段文字时,使用三个单引号或双引号可使字符串跨行显示。如:

helptext="""this a help test.if you have any quesions.
            please call me anytime.I will help you.I
            like python.I hope so as you."""

字符串内部的一个反斜杠“\”可允许把字符串放于多行:如:

>>> "test \
... python"
'test python'

使用上面方法时,反斜杠后面的行不能再缩排表示,因为下一行的空格也包括在字符串中间。为了整个程序的缩排,还是用加号结合换行表示,如:

backupset = 'C:\\Documents and Settings\\Administrator\\Local Settings\\' \
                   + 'Application Data\\Microsoft\\Windows NT\\NTBackup\\sysbak.bks'

字符串支持通过'+'操作符,组合变量和字符串。

print "Your name is " + fullname

函数

replace(string,old,new[,maxsplit])

字符串的替换函数,把字符串中的 old 替换成 new。默认是把 string 中所有的 old 值替换成 new 值,如果给出 maxsplit 值,还可控制替换的个数,如果 maxsplit 为 1,则只替换第一个 old 值。

>>>a="11223344"
>>>print string.replace(a,"1","one")
oneone2223344
>>>print string.replace(a,"1","one",1)
one12223344

find()

查找指定的字符串,如果找到返回找到的字符串,如果没找到返回 -1。

>>> s = "mary had a little lamb"
>>> string.find(s, 'had')
5

count()

计算指定字符串出现的次数。

>>> s = "mary had a little lamb"
>>> string.count(s, 'a')
4

split()

将字符串转成列表,join 可以将列表重新组合成字符串。

>>> s = "mary had a little lamb"
>>> L = string.split(s)
>>> L
['mary', 'had', 'a', 'little', 'lamb']
>>> string.join(L, "-")
'mary-had-a-little-lamb'

lstrip()

去掉行首所有空白字符,包括空格,有制表符 \t 和回车符 \n。类似的 rstrip() 去掉行尾所有空白字符,strip() 去掉前后空白字符。

lower()

字符串转小写字母。

upper()

字符串转大写字母。

capitalize()

该函数可把字符串的首个字符替换成大字。

capwords()

将字符串中所有单词的首字母大写。

ord()

将一个字符(长度为1的字符串)来作为它的参量,并返回该字符的ASCII码或Unicode值。

正则表达式

语法

正则表达式的语法参考 shell scripts。在 Python 中使用正则表达式的步骤为:

  1. 先用 re.compile 得到一个 RegexObject,表示一个 regexp。
  2. 然后用 pattern 的 match, search 的方法,得到 MatchObject。
  3. 再用 match object 得到匹配的位置,匹配的字符信息等。

在 python 中表示 regexp 一般都加上 r ,表示使用原始字符串,这样就不解析 \ 等特殊字符。

>>> a = r"\a"
>>> print a
\a
>>> a = r"\"a"
>>> print a
\"a

函数

compile()

将正则表达式的 pattern 加入到正则表达式对象中。

search()

最常用的函数,返回一个匹配对象(Match Object)。

>>> if re.compile("a").search("abab"): print 'ture'
ture
>>> if re.compile("a").search("bbab"): print 'ture'
ture

match()

类似 search,但仅仅从文字的开始进行匹配。

>>> if not re.compile("a").match("bbab"): print 'false'
false
>>> if re.compile("a").match("abab"): print 'ture'
ture

StringIO/cStringIO

很多模块中的函式都需要一个文件对象作参数,有时候创建一个真的文件很麻烦,可以通过 “StringIO” 模块来创建一个保存在内存中的文件来使用。

import StringIO

fileHandle = StringIO.StringIO("Let freedom ring.")

print fileHandle.read() # "Let freedom ring."

fileHandle.close()

“cStringIO” 模块与 “StringIO” 一样的使用,而且使用更快的 C 语言现实。

import cStringIO

fileHandle = cStringIO.StringIO ("To Kill a Mockingbird")

print fileHandle.read() # "To Kill a Mockingbid"

fileHandle.close()
Currently unrated

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required