校招季——Python笔记三

来源:互联网 发布:underscore.js 下载 编辑:程序博客网 时间:2024/04/29 15:29

三.        字符串

1.     字符串是不可变的。

2.     format类似于C语言printf中使用的格式化控制符,用法是fmt % tuple,只有元组和字典可以格式化多个值,序列只能格式化一个值。

>>> fmt = "hello, %s, %s enough for ya? %d:%f"

>>> values = ("world", "hot", 15, 1.123)

>>> print(fmt % values)

hello, world, hot enough for ya? 15:1.123000

3.     另一种格式化值的方法:模板字符串。string模块的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!"

如果有多个替换字段,可以用字典当作substitute的参数。

4.     字符串方法

1)    find:查找子串,返回子串索引位置或-1。还可以有可选的起始点和结束点参数。

2)    joinsplit方法的逆方法。

>>> sep = '+'

>>> s = ['1', '2', '3', '4', '5']

>>> s.join(seq)

'1+2+3+4+5'

3)    lower:返回字符串的小写字母版。

4)    title:将字符串转为标题——单词首字母大写。另一个capwords函数与它的区别是capwords对单词的划分是用空格而不是标点。

>>> "that's all folks".title()

"That'S All Folks"

>>> string.capwords("that's all folks")

"That's All Folks"

5)    replace:替换子串。

6)    split:分割字符串。如果不提供分隔符,默认会将所有空格作为分隔符。

>>> "1+2+3+4+5+".split('+')

['1', '2', '3', '4', '5', '']

>>> "I'm fine, thank you".split()

["I'm", 'fine,', 'thank', 'you']

7)    strip:返回去除了两侧空格的字符串。也可以传递进要去除的字符。

8)    translate:根据转换表,将字符串中的字符按表中的对应关系进行替换。可以用maketrans函数生成一个转换表。translate的可选参数是指定要删除的字符。

>>> table = str.maketrans('cs', 'kz')

>>> table

{115: 122, 99: 107}

>>> "catch this cat".translate(table)

'katkh thiz kat'

Python3中已经没有string.maketrans了,取而代之的是内建函数bytearray.maketrans()bytes.maketrans()str.maketrans()