《Python基础教程 第2版·修订版》第3章 使用字符串(学习笔记)

来源:互联网 发布:od软件 编辑:程序博客网 时间:2024/05/17 04:24

3.1基本字符串操作
基本字符串操作
所有标准序列的操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串同样适用。唯一不同是字符都是不可变的

3.2字符串格式化:精简版
字符串格式化使用字符串格式化操作符即百分号%来实现
示例如下:

>>> format = "hello,%s,%s enough for ya?">>> values = ('World','Hot')>>> print format % valueshello,World,Hot enough for ya?
>>> format = "Pi with three decimals:%.3f"#格式化浮点数>>> from math import pi>>> print format % piPi with three decimals:3.142

3.3字符串格式化:完整版
示例:

>>> '%s plus %s equals %s' %(1,1,2)'1 plus 1 equals 2'>>> #如果需要转换的元组作为转换表达式的一部分存在,那么必须将它用圆括号括起来,以避免出错

3.3.1简单转换
简单的转换只需要写出转换类型,使用起来很简单

>>> from math import pi>>> 'Pi:%f...' % pi'Pi:3.141593...'

3.3.2字符宽度和精度

>>> '%10f' % pi #字段宽10'  3.141593'>>> '%10.2f' % pi #字段宽10,精度2'      3.14'>>> '%.2f' % pi #精度2'3.14'>>> '%.5s' % 'Guido van Rossum''Guido'

3.3.3 符号、对齐和用0填充

>>> '%010.2f' % pi'0000003.14'
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)   10  -10>>> #而空白意味着在正数前加上空格。这在需要对齐正负数时会很有用
>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)  +10  -10>>> #加号,它表示不管是正数还是负数都标示出符号(同样是在对齐时很有用)

3-1 字符串格式化示例

#使用给定的宽度打印格式化之后的价格列表width = input('Please enter width: ')price_width = 10item_width =  width - price_widthheader_format = '%-*s%*s'format        = '%-*s%*.2f'print '=' * widthprint header_format % (item_width, 'Item', price_width, 'Prce')print '-' * widthprint format % (item_width, 'Apples',price_width,0.4)print format % (item_width, 'Pears',price_width,0.5)print format % (item_width, 'Cantaloupes',price_width,1.92)print format % (item_width, 'Dried Apricots(16 oz.)',price_width,8)print format % (item_width, 'Prunes(4 lbs.)',price_width,12)
Please enter width: 35===================================Item                           Prce-----------------------------------Apples                         0.40Pears                          0.50Cantaloupes                    1.92Dried Apricots(16 oz.)         8.00Prunes(4 lbs.)                12.00>>> 

3.4字符串方法
3.4.1 find
find方法可以在一个较长的字符串中查找子串。它返回子串所在位置的最左端索引。如果没有找到则返回-1

>>> title = "Monty Python's Flying Circus">>> title.find('Monty')0>>> title.find('Python')6>>> title.find('Flying')15

3.4.2 join

>>> seq = ['1','2','3','4','5']>>> sep = '+'>>> sep.join(seq)'1+2+3+4+5'
>>> dirs = '','usr','bin','env'>>> '/'.join(dirs)'/usr/bin/env'

3.4.3 lower
lower方法返回字符串的小写字母版

>>> 'Trondheim Hammer Dance'.lower()'trondheim hammer dance'

3.4.4 replace

>>> 'This is a test'.replace('is','eez')'Theez eez a test'

3.4.5 split

>>> '1+2+3+4+5'.split('+')['1', '2', '3', '4', '5']

3.4.6 strip
strip方法返回去除两侧(不包括内部)空格的字符串

>>> name = '  Nick Feng  '>>> name.strip()'Nick Feng'

3.4.7 translate

>>> table = maketrans('cs','kz')>>> "this is a test".translate(table)'thiz iz a tezt'
0 0
原创粉丝点击