Python 标准库笔记(1) — String模块
原文出处: j_hao104
String模块包含大量实用常量和类,以及一些过时的遗留功能,并还可用作字符串操作。
1. 常用方法
| 常用方法 | 描述 |
|---|---|
| str.capitalize() | 把字符串的首字母大写 |
| str.center(width) | 将原字符串用空格填充成一个长度为width的字符串,原字符串内容居中 |
| str.count(s) | 返回字符串s在str中出现的次数 |
| str.decode(encoding=’UTF-8’,errors=’strict’) | 以指定编码格式解码字符串 |
| str.encode(encoding=’UTF-8’,errors=’strict’) | 以指定编码格式编码字符串 |
| str.endswith(s) | 判断字符串str是否以字符串s结尾 |
| str.find(s) | 返回字符串s在字符串str中的位置索引,没有则返回-1 |
| str.index(s) | 和find()方法一样,但是如果s不存在于str中则会抛出异常 |
| str.isalnum() | 如果str至少有一个字符并且都是字母或数字则返回True,否则返回False |
| str.isalpha() | 如果str至少有一个字符并且都是字母则返回True,否则返回False |
| str.isdigit() | 如果str只包含数字则返回 True 否则返回 False |
| str.islower() | 如果str存在区分大小写的字符,并且都是小写则返回True 否则返回False |
| str.isspace() | 如果str中只包含空格,则返回 True,否则返回 False |
| str.istitle() | 如果str是标题化的(单词首字母大写)则返回True,否则返回False |
| str.isupper() | 如果str存在区分大小写的字符,并且都是大写则返回True 否则返回False |
| str.ljust(width) | 返回一个原字符串左对齐的并使用空格填充至长度width的新字符串 |
| str.lower() | 转换str中所有大写字符为小写 |
| str.lstrip() | 去掉str左边的不可见字符 |
| str.partition(s) | 用s将str切分成三个值 |
| str.replace(a, b) | 将字符串str中的a替换成b |
| str.rfind(s) | 类似于 find()函数,不过是从右边开始查找 |
| str.rindex(s) | 类似于 index(),不过是从右边开始 |
| str.rjust(width) | 返回一个原字符串右对齐的并使用空格填充至长度width的新字符串 |
| str.rpartition(s) | 类似于 partition()函数,不过是从右边开始查找 |
| str.rstrip() | 去掉str右边的不可见字符 |
| str.split(s) | 以s为分隔符切片str |
| str.splitlines() | 按照行分隔,返回一个包含各行作为元素的列表 |
| str.startswith(s) | 检查字符串str是否是以s开头,是则返回True,否则返回False |
| str.strip() | 等于同时执行rstrip()和lstrip() |
| str.title() | 返回”标题化”的str,所有单词都是以大写开始,其余字母均为小写 |
| str.upper() | 返回str所有字符为大写的字符串 |
| str.zfill(width) | 返回长度为 width 的字符串,原字符串str右对齐,前面填充0 |
2.字符串常量
| 常数 | 含义 |
|---|---|
| string.ascii_lowercase | 小写字母’abcdefghijklmnopqrstuvwxyz’ |
| string.ascii_uppercase | 大写的字母’ABCDEFGHIJKLMNOPQRSTUVWXYZ’ |
| string.ascii_letters | ascii_lowercase和ascii_uppercase常量的连接串 |
| string.digits | 数字0到9的字符串:’0123456789’ |
| string.hexdigits | 字符串’0123456789abcdefABCDEF’ |
| string.letters | 字符串’abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’ |
| string.lowercase | 小写字母的字符串’abcdefghijklmnopqrstuvwxyz’ |
| string.octdigits | 字符串’01234567’ |
| string.punctuation | 所有标点字符 |
| string.printable | 可打印的字符的字符串。包含数字、字母、标点符号和空格 |
| string.uppercase | 大学字母的字符串’ABCDEFGHIJKLMNOPQRSTUVWXYZ’ |
| string.whitespace | 空白字符 ‘\t\n\x0b\x0c\r ‘ |
3.字符串模板Template
通过string.Template可以为Python定制字符串的替换标准,下面是具体列子:
Python
|
1
2
3
4
5
6
7
8
9
10
|
>>>from string import Template
>>>s = Template('$who like $what')
>>>print s.substitute(who='i', what='python')
i like python
>>>print s.safe_substitute(who='i') # 缺少key时不会抛错
i like $what
>>>Template('${who}LikePython').substitute(who='I') # 在字符串内时使用{}
'ILikePython'
|
Template还有更加高级的用法,可以通过继承string.Template, 重写变量delimiter(定界符)和idpattern(替换格式), 定制不同形式的模板。
Python
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import string
template_text = ''' Delimiter : $de Replaced : %with_underscore Ingored : %notunderscored '''
d = {'de': 'not replaced',
'with_underscore': 'replaced',
'notunderscored': 'not replaced'}
class MyTemplate(string.Template):
# 重写模板 定界符(delimiter)为"%", 替换模式(idpattern)必须包含下划线(_)
delimiter = '%'
idpattern = '[a-z]+_[a-z]+'
print string.Template(template_text).safe_substitute(d) # 采用原来的Template渲染
print MyTemplate(template_text).safe_substitute(d) # 使用重写后的MyTemplate渲染
|
输出:
Python
|
1
2
3
4
5
6
7
|
Delimiter : not replaced
Replaced : %with_underscore
Ingored : %notunderscored
Delimiter : $de
Replaced : replaced
Ingored : %notunderscored
|
原生的Template只会渲染界定符为$的情况,重写后的MyTemplate会渲染界定符为%且替换格式带有下划线的情况。
4.常用字符串技巧
- 1.反转字符串
|
1
2
3
|
>>> s = '1234567890'
>>> print s[::-1]
0987654321
|
- 2.关于字符串链接
尽量使用join()链接字符串,因为’+’号连接n个字符串需要申请n-1次内存,使用join()需要申请1次内存。
- 3.固定长度分割字符串
|
1
2
3
4
|
>>> import re
>>> s = '1234567890'
>>> re.findall(r'.{1,3}', s) # 已三个长度分割字符串
['123', '456', '789', '0']
|
- 4.使用()括号生成字符串
1234567sql = ('SELECT count() FROM table ''WHERE id = "10" ''GROUP BY sex')print sqlSELECT count() FROM table WHERE id = "10" GROUP BY sex
- 5.将print的字符串写到文件
Python
|
1
|
>>> print >> open("somefile.txt", "w+"), "Hello World" # Hello World将写入文件somefile.txt
|
Python 标准库笔记(1) — String模块的更多相关文章
- (转)Python 标准库笔记:string模块
String模块包含大量实用常量和类,以及一些过时的遗留功能,并还可用作字符串操作. 原文:http://www.10tiao.com/html/384/201709/2651305041/1.htm ...
- Python标准库笔记(1) — string模块
String模块包含大量实用常量和类,以及一些过时的遗留功能,并还可用作字符串操作. 1. 常用方法 常用方法 描述 str.capitalize() 把字符串的首字母大写 str.center(wi ...
- Python标准库笔记(9) — functools模块
functools 作用于函数的函数 functools 模块提供用于调整或扩展函数和其他可调用对象的工具,而无需完全重写它们. 装饰器 partial 类是 functools 模块提供的主要工具, ...
- Python标准库笔记(8) — pprint模块
struct模块提供了用于在字节字符串和Python原生数据类型之间转换函数,比如数字和字符串. Python版本: 2.x & 3.x 该模块作用是完成Python数值和C语言结构体的Pyt ...
- Python标准库笔记(11) — Operator模块
Operator--标准功能性操作符接口. 代码中使用迭代器时,有时必须要为一个简单表达式创建函数.有些情况这些函数可以用一个lambda函数实现,但是对于某些操作,根本没必要去写一个新的函数.因此o ...
- Python标准库笔记(10) — itertools模块
itertools 用于更高效地创建迭代器的函数工具. itertools 提供的功能受Clojure,Haskell,APL和SML等函数式编程语言的类似功能的启发.它们的目的是快速有效地使用内存, ...
- python标准库介绍——4 string模块详解
==string 模块== ``string`` 模块提供了一些用于处理字符串类型的函数, 如 [Example 1-51 #eg-1-51] 所示. ====Example 1-51. 使用 str ...
- Python标准库笔记(6) — struct模块
该模块作用是完成Python数值和C语言结构体的Python字符串形式间的转换.这可以用于处理存储在文件中或从网络连接中存储的二进制数据,以及其他数据源. 用途: 在Python基本数据类型和二进制数 ...
- Python标准库笔记(4) — collections模块
这个模块提供几个非常有用的Python容器类型 1.容器 名称 功能描述 OrderedDict 保持了key插入顺序的dict namedtuple 生成可以使用名字来访问元素内容的tuple子类 ...
随机推荐
- Hyperledger Fabric 建立一个简单网络
Building you first network 网络结构: 2个Orgnizations(每个Org包含2个peer节点)+1个solo ordering service 打开fabric-sa ...
- spring cloud 的自我保护机制
spring cloud 的自我保护机制定义: 自我保护模式是:在出现网络异常波动的情况下,使用自我保护模式使eureka 集群更加健壮,稳定. 自我保护机制是:在15分钟内客户端没有雨注册中心发生心 ...
- 【原创】Arduino制作Badusb实践
1.U盘构造 U盘由芯片控制器和闪存两部分组成. 芯片控制器负责与PC的通讯和识别,闪存用来做数据存储: 闪存中有一部分区域用来存放U盘的固件,它的作用类似于操作系统,控制软硬件交互:固件无 ...
- web 自定义标签
Web Components 标准非常重要的一个特性是,它使开发者能够将HTML页面的功能封装为 custom elements(自定义标签).而自定义标签的好处,就是在大型web开发的时候,可以封装 ...
- PHP下载微信头像
public function downloadPic($openid='',$headimgurl='') { $header = array( 'User-Agent: Mozilla/5.0 ( ...
- Map、Set、List区别
转:https://www.cnblogs.com/jing99/p/6947549.html 提到集合之前,先说说数组Array和集合的区别: (1)数组是大小固定的,并且同一个数组只能存放类型 ...
- 在Raspbian Stretch系统上设置Home Assistant开机启动
较新的Linux发行版趋向于用systemd管理守护进程,如果您不确定系统是否正在使用systemd,您可以使用以下命令进行检查: -o comm= 如果上述命令返回字符串systemd,说明系统正在 ...
- C++中cin.getline与cin.get要注意的地方
cin.getline与cin.get的区别是,cin.getline不会将结束符或者换行符残留在输入缓冲区中.
- 开发Canvas 绘画应用(一):搭好框架
毕业汪今年要毕业啦,毕设做的是三维模型草图检索,年前将算法移植到移动端做了一个小应用(利用nodejs搭的服务),正好也趁此机会可以将前端的 Canvas 好好学一下~~毕设差不多做完了,现将思路和代 ...
- javascript 之 继承
1.传统方式--->原型链 (过多继承了没用的属性) Grand.prototype.lastname = 'zhang' function Grand(); } var grand = ne ...