您的位置:首页 > 编程语言 > Python开发

python基础(6)--字符处理

2012-12-18 18:51 204 查看
[align=center] [/align]
[align=center][/align]
[align=left][/align]
1,字符串处理基本方法

.提取子字符串
[align=left]#法1:使用切片操作[/align]
>>> 'hello world'[2:8]

'llo wo'
[align=left][/align]
[align=left].合并两个字符串[/align]
[align=left]#法1:使用运算符+[/align]
>>> 'hello ' + 'world'

'hello world'
[align=left][/align]
[align=left]#法2: 使用运算符*[/align]
>>> 'hello '*2

'hello hello '
[align=left][/align]
[align=left]#使用join合并多个字符串[/align]
>>> '--'.join(['a','b','c'])

'a--b--c'
[align=left][/align]
[align=left].替换字符串[/align]
[align=left]#法1:使用replace函数[/align]
>>> 'hello world'.replace('world', 'tom')

'hello tom'
[align=left][/align]
[align=left].格式化字符串[/align]
[align=left]#法1: 使用格式化字符串[/align]
>>> 'hello %s %s' % ('world', 'haha')

'hello world haha'
[align=left][/align]
[align=left]#法2: 使用模板[/align]

>>> template = '--<html>--</html>'

>>> template = template.replace('<html>', 'start')

>>> template = template.replace('</html>', 'end')

>>> print template

--start--end

[align=left][/align]
[align=left]#使用模板2[/align]
>>> template = "hello %(key1)s"

>>> template = "hello %(key1)s %(key2)s"

>>> vals={'key1':'value1', 'key2':'value2'}

>>> print(template % vals)

hello value1 value2
[align=left][/align]
[align=left].分解字符串[/align]
>>> 'a b c d'.split() #基本分解

['a', 'b', 'c', 'd']
[align=left][/align]
[align=left]#指定分解符[/align]
>>> 'a+b+c+d'.split('+')

['a', 'b', 'c', 'd']
[align=left][/align]
[align=left]#分解和合并混用[/align]
from sys import *

stdout.write(('.' * 4).join(stdin.read().split('\t')))
[align=left]实战:[/align]
>>> stdout.write(('.' * 4).join(stdin.read().split('\t')))

aa bb cc dd

aa....bb....cc....dd
[align=left][/align]
[align=left][/align]

应用
#文本过滤
.基本方法
#条件程序
def isCond(astr):

'find sub string @fstr from a string @astr'

return (astr.find('root') != -1)

也可以用匿名函数:
isCond lambda astr: astr.find('root') != -1

#文本过滤第一版
def filter1(filename):

'filter every line which read from filename'

selected = []

try:

fp = open(filename)

except IOError, e:

print 'could not open file :', e
for line in fp.readlines():

if isCond(line):

selected.append(line)

print selected

#文本过滤第2版,使用filter内建函数
def filter2(filename):

'filter version 2'

selected = []

selected = filter(isCond, open(filename).readlines())

print selected

.使用map函数
map(isCond, open(filename).readline())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: