《Python基础教程》学习笔记——字符串

序列的通用操作,加、乘、成员资格、最值、长度都适用于字符串

----------字符串格式化----------

用%来实现:在%的左侧放置一个格式化字符串,右侧放置希望格式化的值。
值可以是数字、字符串,也可以是元组或字典
如果使用列表或者其他序列代替元组,那么序列就会被解释为一个值
只有元组字典可以格式化一个以上的值。

formatStr = "Hello, %s. %s enough for ya?"
values = ('world','Hot')
print formatStr % values

如果要格式化实数(浮点数),可以使用f说明符类型,同时提供所需要的精度

formatStr1 = "Pi with three decimals: %.3f"
print formatStr1 % math.pi

string模块提供了另外一种格式化值的方法:模板字符串
用到了Template对象 和substitute方法

s = string.Template('$x,glorious $x!')
print s.substitute(x='slurm')

如果替换字段是单词的一部分,那么参数名就必须用{}括起来

s = string.Template("It's ${x}tastic!")
print s.substitute(x = 'slurm')

可以使用$$插入美元符号:

s = string.Template("make $$ selling $x!")
print s.substitute(x = 'slurm')

可以使用字典

s = string.Template('A $thing must never $action.')
d = {}
d['thing'] = 'gentleman'
d['action'] = 'show his socks'
print s.substitute(d)

----------字符串方法-*--------*-

sting模块中的常量

print string.digits  #包含数字0~9的字符串
print string.letters #包含所有字母(大写或小写)的字符串
print string.lowercase #包含所有小写字母的字符串
print string.printable #包含所有可打印字符的字符串
print string.punctuation #包含所有标点的字符串
print string.uppercase #包含所有大写字母的字符串

1.find方法:在一个较长的字符串中查找子字符串,返回子串所在位置的最左端索引,如果找不到,就返回-1

title = "Monty Python's Flying Circus"
print title.find('Monty')
print title.find('other')

subject = '$$$ Get rich now!!! $$$'
print subject.find('$$$')

find方法还可以接受可选的起始点和结束点参数,用来指定查找范围

print subject.find('$$$',1)
print subject.find('!!!',0,16)

2.join方法:是split方法的逆方法,用来在队列中添加元素,需要添加的队列元素都必须是字符串,返回的是字符串

seq = ['1','2','3','4','5']
sep = '+'
print sep.join(seq)

dirs = '','usr','bin','env'
print '/'.join(dirs)

print 'C:'+'\\'.join(dirs)

3.lower :返回字符串的小写字母版本

str1 = 'Trondheim Hammer Dance'
print str1.lower()

4.replace:返回某字符串的所有匹配项均被替换之后得到的字符串

str2 = 'This is a test is is'
print str2.replace('is','eez')

5.split:用来将字符串分割成序列

print '1+2+3+4+5'.split('+')
print ' /usr/bin/env'.split('/')

如果不提供分隔符,就会将空格作为分隔符

print 'Using the default'.split()

6.strip:返回去除两侧(不包含内部)空格的字符串

print '     internal whitespace is kept     '.strip()

也可以用来删除两侧指定的字符

print '***** SPAM * for * everyone!!! ****'.strip(' *!')

7.translate

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值