Python标准库(1)——string
来源:互联网 发布:手机怎么注销淘宝账号 编辑:程序博客网 时间:2024/06/18 10:16
1 字符串部分1.1 string 包含常量及文字处理类1.1.1 函数capwords()函数将字符串中的每一个单词的首字母大写>>> print string.capwords('my name is lxg')My Name Is Lxg该函数的功能类似于调用字符串的split()函数,将每个单词首字母大写,然后调用join()方法将单词拼接起来>>> print ' '.join([s.capitalize() for s in 'my name is lxg'.split()])My Name Is Lxg与str.capitalize()函数不同,str.capitalize()函数只将字符串的第一个单词的首字母大写>>> print 'my name is lxg'.capitalize()My name is lxgmaketrans()函数可以创建一个转换表,然后调用str.translate()方法可以使用该转换表>>> table = string.maketrans('abcdefg', '1234567')>>> 'my name is lxg'.translate(table)'my n1m5 is lx7'从输出可以看出,字母a转换成1,字母e转换成5, 字母g转换成71.1.2 Templatesstring.Template可以对字符串中的命名参数进行变量替换>>> template = string.Template('my name is ${name}')>>> template.substitute({'name':'lxg'})'my name is lxg'从输出可以看出,模板中的name变量被替换成了lxg1.3 re 正则表达式库,用于正则表达式的模式匹配和查找1.3.1 模式查找。最常用的方式是在一段文本中查找特定的模式。search(pattern, text)接受两个参数。如果模式匹配,则返回一个Match对象;否则返回None每一个Match对象都包含了该模式匹配的一些基本信息,包括最初传入的字符串,使用的正则表达式,以及匹配的模式在字符串中的位置。>>> import re>>> pattern = 'lxg'>>> text = 'my name is lxg'>>> match = re.search(pattern, text)>>> print 'Found "%s"\nin "%s"\nfrom %d to %d' % (match.re.pattern, match.string, match.start(), match.end())Found "lxg"in "my name is lxg"from 11 to 141.3.2 编译正则表达式。compile()方法可以将一段正则表达式编译成一个RegexObject对象>>> regex = re.compile('lxg')>>> match = regex.search('my name is lxg')>>> print 'Found "%s"\nin "%s"' % (match.re.pattern, match.string)Found "lxg"in "my name is lxg"1.3.3 多结果匹配。findall()方法可以返回所有的匹配结果。finditer()方法也可以返回所有的匹配结果,区别是结果为Match对象,而不是string>>> for match in re.findall('lxg', 'my name is lxg and lxg is my name'):... print 'found %s' % match...found lxgfound lxg>>> for match in re.finditer('lxg', 'my name is lxg and lxg is my name'):... print 'found at %d-%d' % (match.start(), match.end())...found at 11-14found at 19-22
0 0
- Python标准库(1)——string
- Python 标准库 —— string
- [Python标准库]string——文本常量和模板
- 标准库类型基础(1)— string
- Python 标准库笔记:string模块
- 《c++ primer》-——1 标准库string类型
- C++标准库类型——string类型(一)
- C++标准库——字符串(Standard library: String)
- C++标准库类型——string
- C 标准库—— string.h
- 标准库类型——string
- C++标准库类型——string
- python3 标准库——string
- 第三章 标准库string、vector、bitset类型 —— 第一节 标准库string类
- C++ primer 读书笔记系列——(1)标准库string类型
- python标准库1
- Python标准库(2)——数据结构之Counter
- Python标准库(3)——数据结构之defaultdict
- javap:count = count ++
- 【c语言】 my_strcpy 实现字符串拷贝
- 免安装版mysql配置
- 将装了win的mac重装回来具体步骤
- EGOTableViewPullRefresh下拉原理及代码详解
- Python标准库(1)——string
- PPT转换成视频软件(iSpring Suite)V7.0.1 X32 免费无限制版
- String扩展 让你在PadLeft和PadRight时不再受单双字节问题困扰
- Android访问/data/app/下文件方法
- Eclipse Hover 提示过快
- Android Studio 快捷键大全
- Python标准库(2)——数据结构之Counter
- CentOS 6.5 源码安装Nginx1.6.3
- 黑马程序员——异常