Python基础学习(字符串)

字符传格式化

字符传格式化经过占位符'%'实现,通常状况下使用元组对占位符进行替换
python

若是要格式化的字符串包括符号‘%’,则必须使用%%app

from math import pi
print '这是百分号%%,这是pi的近似值:%08.2f' % pi
print '这是百分号%%,这是pi的近似值:%+8.2f' % -pi
print '这是百分号%%,这是pi的近似值:%-*.2f' % (8,pi)
print '这是百分号%%,这是pi的近似值:%.*s' % (4,'aaaaaa')

在要格式化的字符串中,占位表达式‘%08.2f‘中,f表示是浮点数,'.2'表示小数点的精度,小数点前一位数字表示替换数值的保留位数,不足则在左边补0(即%后的0)
this

字符串中整个占位表达式的参数说明以下:spa

  • %字符:标记占位符替换的起始部分code

  • 转换标识符(可选):上例中是%后的0,-表示左对齐,+表示在转换值以前加正负,“”(空白字符)表示在正数以前保留空格,0表示转换后若位数不够则用0填充索引

  • 最小字段宽度(可选):转换后字符串至少应该具备该指定宽度,若是是*号,则宽度从元组中取出ip

小数点(.)后跟精度(可选):若是转换的是实数,精度值就表示小数点后位数;若是转换的是字符串,那么该精度值表示的是转换后的最大字宽,若是是*,则从该值元组中取出字符串

使用给定输入打印一个简版的价格表
input

#使用给定宽度打印价格列表
total_width=input('input width:')
price_width=10
item_width=total_width-price_width
print '='*total_width
print '%-*s%*s' %(item_width,'item',price_width,'price')
print '-'*total_width
print '%-*s%*.2f' %(item_width,'apple',price_width,2.8888)
print '-'*total_width
print '%-*s%*.2f' %(item_width,'pear',price_width,8)
print '-'*total_width
print '%-*s%*.2f' %(item_width,'orange',price_width,pi)
print '='*total_width

字符串方法

前面介绍过一些列表及序列方法,这里介绍一部分字符串方法string

find:在一个较长字符串中查找子字符串,返回子字符串所在位置的最左端索引,未找到则返回-1,这里in关键字只能判断单一字符是否在指定字符串中

strTest='hello, world!'
print strTest.find('lo')
#从指定索引开始查询
print strTest.find('l',5)
#包左不包右,查询指定范围的字符索引
print strTest.find('l',4,10)

join(seq):将某一字符串序列seq,按照指定的字符串拼接成一个字符串返回

temp = '-'.join(['a','b','c','d'])
print temp #a-b-c-d

split(separator):将某一字符串按照指定的字符separator分割,返回一个列表,不改变原字符串

var = 'test'.split('es')
print var #['t', 't']

lower:将字符串转化为小写

test='ABCD'
print test.lower()

replace:该方法会返回一个被替换后的新字符串

print test.replace('AB', 'ab')

strip:该方法返回去除两侧(不包括内部)空格的字符串,也能够指定须要去除的字符

test='***this is a test!***'
print test
print test.strip('*')

translate: translate方法和replace方法同样能够替换字符串中的某些部分,可是translate方法只处理单个字符,能够同时进行多个替换,有时候比replace高效

from string import maketrans
#maketrans的两个参数必须是等长的,对应位置的替换表
tab = maketrans('es', '* ')
tem = 'testabc'
#第二个参数用于指定要删除的字符
va = tem.translate(tab,'b')
print va
print tem
相关文章
相关标签/搜索