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

Python开发技术详解-笔记_第06章-字符串与正则表达式

2013-10-23 15:40 946 查看
6. 字符串 与 正则表达式

- 字符串的格式化

- 字符串的截取、合并、过滤 等

- 字符串的查找

- 正则表达式的语法

- Python的正则表达式模块



6.1 字符串的操作

6.1.1 字符串的格式化

(1) 作用

Python将若干值插入带有"%"标记的字符串中,

从而可以动态地输出字符串.

(2) 格式

①单个



"%s" % myStr1

②多个-元组

"%s %s" % (myStr1, myStr2)

③字典

"%(key1)s %(key2)s" % {"key1":"value1", "key2":"value2"}

(3) 替代符

%s 字符串

%d 整型

%f 浮点型

... ...

(4) 字符串的对齐操作

① str.center(width[, fillchar])

>>> "abc".center(10)

' abc '

>>> "abc".center(10,"*")

'***abc****'

② str.ljust(width[, fillchar])

>>> "abc".ljust(10)

'abc '

③ str.rjust(width[, fillchar])

>>> "abc".rjust(10)

' abc'

6.1.2 字符串的转义符

字符: 可见 和 不可见

可见字符: 键盘行的字符键

不可见字符: 换行符、回车符 等

"\" 来转义

(1) 注意

Python中 制表符 占一个字符

(2) Python 支持转义字符

\' \"

\a 系统响铃 \b 退格

\n 换行 \t 横向指标

\v 纵向制表 \r 回车

\f 换页 \o 八进制

\x 十六进制 \000 终止符,其后的字符串全部忽略

(3) 去字符串前后转义字符

- str.strip([chars]) 去 左和右

- str.lstrip([chars]) 去 左

- str.rstrip([chars]) 去 右

>>> print " abc \n\n"

abc



>>> print " abc \n\n".strip()

abc

6.1.3 字符串的合并

- "+"

- S.join(iterable) -> string

- reduce()

(1) " + "

① 两侧都是字符串类型, 则连接

② 两侧都是数字, 则加法

③ 两侧不同类型, 抛异常



(2) S.join(iterable) -> string

Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.

>>> "#".join(['1','2','3'])

'1#2#3'

>>> "".join(['1','2','3'])

'123'



(3) reduce()

>>> reduce(lambda x,y : x+y, ['a', 'b', 'c'], '')

'abc'

>>> import operator

>>> reduce(operator.add, ['a', 'b', 'c'], '')

'abc'

6.1.4 字符串的截取

- 索引, 切片

- S.split([sep [,maxsplit]]) -> list of strings



(1) 切片

string[start : end : step]

>>> "0123456779"[0:3]

'012'

>>> "0123456779"[:3]

'012'

>>> "0123456779"[::3]

'0369'

(2) split

#默认空格分隔

>>> "1 2 3 4".split()

['1', '2', '3', '4']

>>> "1 2 3 4".split(" ", 2)

['1', '2', '3 4']

6.1.5 字符的比较

- 用 "==" "!=" 比较

- cmp(x, y) -> integer

- startswith() endswith()

(1) "==" "!="

>>> "123" == "123"

True

>>> "123" == "12"

False

(2) cmp(x, y)

>>> cmp("123", "123")

0

>>> cmp("123", "12")

1

>>> cmp("12", "123")

-1

(3) S.startswith(prefix[, start[, end]]) -> bool

S.endswith(suffix[, start[, end]]) -> bool

>>> "123456789".startswith("123")

True

>>> "123456789".startswith("124")

False

>>> "123456789".endswith("789")

True

>>> "123456789".endswith("789l")

False

6.1.6 字符串的反转

- 遍历每个字符, 然后拼接起来

- 切片

(1) 遍历

>>> def func(str) :

... temp = ""

... for x in xrange(0, len(str)) :

... temp = str[x] + temp

... return temp

...

>>> func("123")

'321'

(2) 切片 -- str[::-1]

>>> "123"[::-1]

'321'

6.1.7 字符串的查找和替换

- 查找

- S.find(sub [,start [,end]]) -> int, -1 on failure.

- S.rfind(sub [,start [,end]]) -> int

- 替换

- S.replace(old, new[, count]) -> string

(1) 查找

# 从左找 第一个 符合要求的

>>> "00x00000x000000".find("x")

2

# 从右找 第一个 符合要求的

>>> "00x00000x000000".rfind("x")

8

(2) 替换

>>> "aaaaaaa".replace("a", "b")

'bbbbbbb'

>>> "aaaaaaa".replace("a", "b", 3)

'bbbaaaa'

6.1.8 字符串与日期的转换

- 时间 转 字符串

time.strftime(format[, tuple]) -> string

- 字符串 转 时间

(1) 时间 转 字符串

① 语法

import time

time.strftime(format[, tuple]) -> string

② formatting codes



③ 举例

# 当前系统时间

>>> time.localtime()

time.struct_time(tm_year=2013, tm_mon=10, tm_mday=21, tm_hour=17, tm_min=51, tm_sec=27, tm_wday=0, tm_yday=294, tm_isdst=0)

>>> time.strftime("%Y-%m-%d", time.localtime())

'2013-10-21'

(2) 字符串 转 时间

① 语法

# Parse a string to a time tuple according to a format specification.

import time

time.strptime(string, format) -> struct_time

# get the values of [year month day] from tuple

year,month,day = struct_time[0:3]

# constructe a date object

import datetime

datetime.datetime(year, month, day)



② 举例

>>> import time

>>> timeTuple = time.strptime("2013-1-22", "%Y-%m-%d")

>>> timeTuple

time.struct_time(tm_year=2013, tm_mon=1, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=22, tm_isdst=-1)

>>> year,month,day = timeTuple[0:3]

>>> import datetime

>>> dateObj = datetime.datetime(year, month, day)

>>> dataObj

datetime.datetime(2013, 1, 22, 0, 0)

6.2 正则表达式

正则表达式用于搜索、替换、解析 字符串.

6.2.1 正则表达式简介

(1) 简介

正则表达式是用于文本匹配的工具,

在源字符串中查找给定的正则表达式相匹配的部分.

一个正则表达式的组成: 字母、数字、特殊字符

其中, 特殊字符是构成正则表达式的要素.



(2) 特殊字符串(部分)

^ 开始字符

$ 结束字符

\w 匹配字母、数字、下划线

\W 匹配不是字母、数字、下划线

\s 匹配空白字符

\S 匹配不是空白的字符

\d 匹配数字

\D 匹配非数字的字符

\b 匹配单词的开始和结束

\B 匹配不是单词开始和结束的位置

. 匹配任意字符, 包括汉字

[m] 匹配单个字符

[m1m2...mn] 匹配多个字符中的一个

[m-n] 匹配m到n区间内的数字、字母

[^m] 匹配除m以外的字符串

() 对正则表达式进行分组,一对圆括号表示一组.

(3) 限定符 - 重复

* 匹配零次或多次

+ 匹配一次或多次

? 匹配一次或零次

{m} 重复m次

{m, n} 重复m到n次,n缺省为 无限次

(4) 转义字符

"\"

(5) 分组

每个左圆括号代表一个组, 组号从1开始

如 搜索"aba"

>>> re.search(r"(a)b\1", "aba").group(0)

'aba'

(6) 最长匹配 和 最短匹配

最长匹配: 正则表达式默认是最长匹配

最短匹配: 通过在限定符后面添加"?",获取最短匹配的结果



# 最长

>>> re.findall(r"a+", "aaa")

['aaa']

# 最短

>>> re.findall(r"a+?", "aaa")

['a', 'a', 'a']

(7) 限定符与 "?" 的组合

*?

+?

??

{m, n}? 重复m次

(?#.....) 正则表达式中的注释

(?P<groupname>regex) 给分组命名,name为分组的名称

(?P=groupname) 使用分组名为name的分组

注: (?P<name>regex) (?P=name) 是Python中的写法.

>>> re.findall(r"(?# my regex )a+?", "aaa")

['a', 'a', 'a']

>>> re.search(r"(?P<myGroup>a)b", "aba").group(0)

'ab'

>>> re.search(r"(?P<myGroup>a)b(?P=myGroup)", "aba").group(0)

'aba'

6.2.2 使用 sys.re 模块处理正则表达式

(1) 常用函数

findall(pattern,string,flags=0) --> list

返回包含匹配结果的列表.但有分组时,列表由元组组成.



sub(pattern, replace, string, count=0) --> newstring

替换

subn(pattern, replace, string, count=0) --> tuple(newstr,num) 替换,返回新串和替换的次数

match(pattern, string, flags=0) --> a match object

从头匹配,即索引为0的位置不在匹配字符里则返回None

search(pattern, string, falgs=0) --> a match object

找到第一个匹配的字符串,否则返回None

compile(pattern, flags=0) --> a pattern object

编译正则表达式

split(pattern, string, maxsplit=0) --> list

切割



escape(pattern)

Escape all non-alphanumeric characters in pattern.

>>> re.escape("abc+?")

'abc\\+\\?'

(2) flags 参数 - 设置匹配时的附加选项

I / IGNORECASE 忽略大小写

L / LOCALE 字符集本地化

M / MULTILINE 多行匹配,^$匹配每行的开始和结束

S / DOTALL 是"." 匹配所有字符

X / VERBOSE 忽略正则表达式中的空白 换行,以便注释

U / UNICODE

(3) pattern对象的属性和方法

参考文档 7.2.3. Regular Expression Objects

(4) match对象的方法和属性

参考文档 7.2.4. Match Objects
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: