Python学习笔记05
2016-04-21 10:16
555 查看
chapter_5
raw字符串抑制转义
字符串的第一引号的前面出现字母r(大写或小写),它将会关闭转义机制.>>> myfile = open(r'C:\new\text.data','w') >>> >>> myfile = open('C:\\new\\text.data','w') #等价于上面
扩展分片:第三个限制值
>>> S = 'abcdefghijklmnop' >>> S[1:10:2] #偏移值1~9之间,间隔一个元素 'bdfhj' >>> S[::2] #间隔一个元素取字符 'acegikmo'
也可以使用负数作为步进
>>> S = 'hello' >>> S[::-1] #步进-1表示分片将会从右至左进行,实际效果就是将序列进行反转 'olleh'
>>> S = 'abcedfg' #结果为反转输出偏移为5,4,3,2的元素 >>> S[5:1:-1] 'fdec'
分片对象实现分片
>>> 'spam'[1:3] 'pa' >>> 'spam'[slice(1,3)] #用分片对象来实现分片 'pa' >>> 'spam'[::-1] 'maps' >>> 'spam'[slice(None,None,-1)] 'maps'
分片的应用
#文件: echo.py import sys print(sys.argv) #运行结果: % python echo.py -a -b -c ['echo.py','-a','-b','-c']
这里,sys.argv[1:]返回所期待的列表[‘-a’,’-b’,’-c’]
去掉换行字符常常采用的方式
>>> line = 'hello\n' >>> line[:-1] #方式一 >>> line.rstrip #方式二
字符串ASCII转换
>>> ord('s') #字符转ASCII 115 >>> chr(115) #ASCII转字符 's'
修改字符串的方式
方式一:>>> S = 'xxxxSPAMxxxxSPAMxxxx' >>> S.replace('SPAM','EGGC') #替换,生成新的对象,但不会改变原来的对象 'xxxxEGGCxxxxEGGCxxxx' >>> S.replace('SPAM','EGGC',1) #替换一个,从左到右优先 'xxxxEGGCxxxxSPAMxxxx' >>> S.replace('SPAM','EGGC',2) #替换两个 'xxxxEGGCxxxxEGGCxxxx' >>> S 'xxxxSPAMxxxxSPAMxxxx'
方式二:
#思路:将不可变对象(字符串)转为可变对象后再修改,修改完成后再拼接回来 >>> S = 'Spammy' >>> L = list(S) >>> L ['S', 'p', 'a', 'm', 'm', 'y'] >>> L[3] = 'x' >>> L[4] = 'x' >>> L ['S', 'p', 'a', 'x', 'x', 'y'] >>> S = ''.join(L) #拼接列表元素,中间不用字符间隔 >>> S 'Spaxxy'
字符串转列表
>>> line1 = 'aaa bbb ccc' >>> line = 'aaa bbb ccc' >>> cols = line.split() #字符串转列表,元素以空格区分 >>> cols ['aaa', 'bbb', 'ccc'] >>> line = 'aaa,bbb,ccc' >>> cols = line.split(',') #字符串转列表,元素以逗号区分 >>> cols ['aaa', 'bbb', 'ccc']
实际应用
>>> line = "The knights who say Ni!\n" >>> line.rstrip() #去除右边的空格 'The knights who say Ni!' >>> line.upper() 'THE KNIGHTS WHO SAY NI!\n' >>> line.isalpha() False >>> line.endswith('Ni!\n') True >>> line.startswith('The') True
格式化字符串
>>> 'That is %d %s bird' % (1, 'dead') 'That is 1 dead bird'
>>> exclamation = "Ni" >>> "The knights who say %s!" % exclamation 'The knights who say Ni!' >>> "%d %s %d you" % (1,'spam',4) '1 spam 4 you' >>> "%s -- %s -- %s" % (42, 3.14159, [1,2,3]) '42 -- 3.14159 -- [1, 2, 3]'
如果宽度和精度需要在运行过程中计算得出,可以在格式化字符串中用 * 号来指定通过计算得出的精度和宽度
>>> '%f,%.2f,%.*f' % (1/3.0, 1/3.0, 4, 1/3.0) #最后一个保留4位精度 '0.333333,0.33,0.3333' >>> '%f,%.2f,%.*f' % (1/3.0, 1/3.0, 4, 1/3.0) #最后一个保留1位精度 '0.333333,0.33,0.3333'
基于字典的格式化字符串
>>> "%(n)d %(x)s" % {"n":1, "x":"spam"} '1 spam'
基本原理:上例中,格式化字符串里 (n) 和 (x) 引用了右边字典中的键,并提取它们相应的值.生成类似HTML或XML的程序往往利用这一技术.实际应用中,你可以建立一个数值字典,并利用一个基于键的引用的格式化表达式一次性替换它们.
应用:
#构建格式化字符串 >>> reply = """ ... Greetings... ... Hello %(name)s! ... Your age squared is %(age)s ... """ >>> values = {'name': 'Bob', 'age': 40} #构建字典 >>> print(reply % values) #一次性替换 Greetings... Hello Bob! Your age squared is 40
>>> '%(plat)10s = %(item)-10s' % dict(plat = sys.platform, item = 'laptop') ' linux = laptop '
#####小技巧
内置函数vars()返回一个字典,该字典包含所有在本函数调用时存在的变量
>>> food = 'spam' >>> age = 40 >>> vars() {'__spec__': None, 'line': 'The knights who say Ni!\n', 'reply': '\nGreetings...\nHello %(name)s!\nYour age squared is %(age)s\n', 'exclamation': 'Ni', 'values': {'name': 'Bob', 'age': 40}, 'age': 40, 'food': 'spam', '__doc__': None, '__name__': '__main__', '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>} >>> "%(age)d %(food)s" % vars() #根据构建的字典取值 '40 spam'
新的格式化字符串 – format方法
使用主体字符串作为模板,接受任意多个需要替换的参数.在主体字符串中,用花括号 {} 包含位置或关键字(如:{1},{food})指出替换的目标.>>> template = '{0},{1} and {2}' >>> template.format('spam','ham','eggs') #按位置替换 'spam,ham and eggs' >>> template = '{motto}, {pork} and {food}' >>> template.format(motto = 'spam', pork = 'ham', food = 'eggs') #按关键字替换 'spam, ham and eggs' >>> template = '{motto}, {0} and {food}' >>> template.format('ham',motto = 'spam', food = 'eggs') #按位置和关键字替换 'spam, ham and eggs'
format方法添加键,属性和偏移量
键,属性>>> import sys >>> 'My {1[spam]} runs {0.platform}'.format(sys,{'spam': 'laptop'}) #注意第一个替换,和字典键索引有点区别 'My laptop runs linux' >>> 'My {config[spam]} runs {sys.platform}'.format(sys = sys, config={'spam':'laptop'}) 'My laptop runs linux'
偏移量
>>> somelist = list('SPAM') >>> somelist ['S', 'P', 'A', 'M'] >>> 'first = {0[0]}, third = {0[2]}'.format(somelist) 'first = S, third = A' >>> 'first = {0}, last = {1}'.format(somelist[0],somelist[-1]) 'first = S, last = M' >>> parts = somelist[0], somelist[-1], somelist[1:3] #构建元组 >>> 'first = {0}, last = {1}, middle = {2}'.format(*parts) #解包元组做参数 "first = S, last = M, middle = ['P', 'A']"
具体格式化
在替换目标的标识之后使用一个冒号,后面跟着可以指定字段大小,对齐方式和一个特定类型编码的格式化声明.>>> '{0:10} = {1:10}'.format('spam',12.4567) #冒号后面的内容表示占10位空间大小,字符串默认左对齐,数字默认右对齐 'spam = 12.4567' >>> '{0:>10} = {1:<10}'.format('spam',123.4567) # '>'表示右对齐,'<'表示左对齐,'^'表示居中对齐,'='表示一个标记字符后的补充 ' spam = 123.4567 ' >>> '{0.platform:>10} = {1[item]:<10}'.format(sys,dict(item = 'laptop')) ' linux = laptop '
>>> '{0:e},{1:.3e},{2:g}'.format(3.14159,3.14159,3.14159) #冒号后面表示显示的格式,依次为指数形式,3位小数的指数形式,默认的浮点数形式 '3.141590e+00,3.142e+00,3.14159' >>> '{0:f},{1:.2f},{2:06.2f}'.format(3.14159,3.14159,3.14159) #最后一个表示6字符宽度并且左边补充0 '3.141590,3.14,003.14'
>>> '{0:X},{1:o},{2:b}'.format(255,255,255) #16进制,8进制,2进制 'FF,377,11111111' >>> bin(255),int('11111111',2),0b11111111 ('0b11111111', 255, 255) >>> hex(255),int('FF',16),0xFF ('0xff', 255, 255) >>> oct(255),int('377',8),0o377 ('0o377', 255, 255)
>>> '{0:.{1}f}'.format(1/3.0, 4) #动态决定精度 '0.3333' >>> '%.*f' % (4, 1/3.0) '0.3333'
内置format方法
>>> '{0:.2f}'.format(1.2345) '1.23' >>> format(1.2345,'.2f') #用内置format方法来对单独的项进行格式化 '1.23' >>> '%.2f' % 1.2345 '1.23'
对比
>>> data = dict(platform = sys.platform, spam = 'laptop') >>> 'My {spam:<8} runs {platform:>8}'.format(**data) #等价于下面,用键值引用替换 'My laptop runs linux' >>> 'My {spam:<8} runs {platform:>8}'.format(platform = sys.platform, spam = 'laptop') 'My laptop runs linux' >>> 'My %(spam)-8s runs %(platform)8s' % data #直接用字典替换 'My laptop runs linux'
相关文章推荐
- python psutil 进行系统管理 no.2
- Python for Informatics 第11章之正则表达式(四)
- python的argparse模块
- Python for Informatics 第11章之正则表达式(二)
- Python正则表达式指南
- Python for Informatics 第11章 正则表达式(一)
- Python学习(19)正则表达式
- python判断某个模块是否有某个方法
- 推荐用于Web开发的最好 Python 框架
- Python学习(18)面向对象
- python的面向对象基础
- Python = "我为什么开始学Python"
- python psutil 进行系统管理 no.1
- Python爬虫入门笔记(序)
- 利用Google Analytics Api 获取数据——Google-api-python-client配置问题(二)
- python 深浅拷贝
- 使用 Python 实现命令行词典(一)
- Pydev环境搭建ZendStudio 13+python
- python入门(七)
- 用python2来AC!