python学习笔记(3)字符串

本篇主要记录学习使用字符串的笔记。

1 字符串基本操作
所有标准的序列操作(索引、分片、乘法、in、长度、最大值、最小值)对字符串同样适用,但是字符串是不可变的,所以不可进行分片赋值。

2 字符串格式化
在%的左侧放置一个字符串(需要格式化的字符串),而右侧则放置希望格式化的值,可以使用一个值,也可以使用多个值的元组或字典:

>>> format='hello,%s,%s enough for ya?'
>>> values=('word','hot')
>>> print format % values
hello,word,hot enough for ya?
>>> 

只有元组和字典可以格式化一个以上的值。

3 模板字符串

可以利用substitute这个模板方法进行格式化:

>>> from string import Template
>>> s=Template('$x,glorious $x!')
>>> s.substitute(x='slurm')
'slurm,glorious slurm!'

如果要替换单词的一部分,则需要对参数用括号:

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

还可以使用字典变量提供值/名称对:

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

可以用*作为字段宽度或精度,此时数值会从元组参数中读出:

>>> '%.*s' % (5,'Guido van Rossum')
'Guido'
>>> 

其他一些参数:

'%010.2f'表示字段宽度为10,并且用0进行填充空位;
'%-10.2f'表示左对齐数值;
'% 5d'表示在正数前加上空格,用于对齐正负数;
'%+5d'表示不管是正数还是负数都标示出符号

4 字符串查找
find方法可以在一个较长的字符串中查找子字符串,返回子串所在位置的最左端索引,没有找到返回-1:

>>> title="Monty Python's flying circus"
>>> title.find('Python')
6
>>> title.find('python')
-1
>>> title.find("Python's flying")
6
>>> 

find可设定起始点和结束点参数:

>>> title.find('Python',7,10)
-1
>>> 

注:由起始和终止值指定的范围(第二和第三个参数)包含第一个索引,不包含第二个索引,这是Python中的惯例。

5 字符串的连接
join连接字符串列表

>>> seq=['1','2','3']
>>> sep='+'
>>> sep.join(seq)
'1+2+3'
>>> 

6 字符串转换成小写
lower方法返回字符串的小写字母版:

>>> name='DWJ'
>>> name.lower()
'dwj'
>>> name
'DWJ'
>>> name=name.lower()
>>> name
'dwj'
>>> 

7 字符串替换
(1)replace方法返回某字符串的所有匹配项均被替换之后得到字符串:

>>> st='this is a test'
>>> st.replace('is','eez')
'theez eez a test'
>>> st
'this is a test'
>>> 

(2)translate也可以进行替换,但是只处理单个字符,优势在于可以同时进行多个替换,同时也可以删除不需要的字符:

>>> from string import maketrans
>>> table=maketrans('cs','kz')
>>> name='this is an incredible test'
>>> name.translate(table)
'thiz iz an inkredible tezt'
>>> name
'this is an incredible test'
>>> name.translate(table,' ')
'thizizaninkredibletezt'
>>> 

8 字符串的切割
split方法用来将字符串分割成序列:

>>> st
'this is a test'
>>> st.split(' ')
['this', 'is', 'a', 'test']
>>> st
'this is a test'
>>> 

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

>>> ' internal kept  '.strip()
'internal kept'
>>> 

当然strip()里可以填参数,如strip(‘!’)表示去除两侧的!号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值