python笔记三-使用字符串

1、所有序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串同样适用,但是字符串是不可变的,不能对字符串的内容进行修改。

2、对于赋值的字符串参数数组,一般使用元组来保存,例如下面的values

>>> formats = 'hello,%s.%s enoughfor ya'

>>> values=('world','Hot')

>>> print(formats%values)

hello,world.Hot enough for ya

3、如果要格式化实数,可以使用f说明转换说明符的类型,同时提供所需要的精度,如下的%.3f

>>> fmt = 'Pi with three decimals:%.3f'

>>> from math import pi

>>> print(fmt%pi)

Pi with three decimals: 3.142

4、字符子串查找,成功返回子串索引,失败返回-1

>>> title = 'hello,python!'

>>> title.find('python')

6

>>> title.find('aaa')

-1

5、字符串大小写转换函数

>>> str = 'WELCOME'

>>> str.lower()

'welcome'

>>> str

'WELCOME'

>>> str_lower = str.lower()

>>> str_lower

'welcome'

>>> str_upper = str_lower.upper()

>>> str_upper

'WELCOME'

>>> 

6、字符串转换

>>> str = 'hello,world!'

>>> str.replace('world','python')

'hello,python!'

7、字符串连接,注意需要被连接的序列元素必须是字符串

>>> seq = [1,2,3,4,5]

>>> sep = '+'

>>> sep.join(seq)

Traceback (most recent call last):

 File "", line 1, in

   sep.join(seq)

TypeError: sequence item 0: expected strinstance, int found

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

>>> sep = '+'

>>> sep.join(seq)

'1+2+3+4+5'

>>> 

8、字符串的分割

>>> str = '1+2+3+4+5'

>>> str.split('+')

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

9、去除字符串二侧的空格

>>> str = '1+2+3+4+5'

>>> str.split('+')

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

>>> str = '     hello,python!     '

>>> str.strip

>>> str.strip()

'hello,python!'

10、字符转换的批处理

(1)使用translate方法,与replace不同,translate只处理单个字符,可以进行多行替换,有时候比replace效率高得多

(2)在使用translate之前,需要先完成一张转换表,转换表是以某字符串替换某字符的对应关系。由于此表有多达256个项目,可以使用字符串的内建函数maketrans(Python 3.x)。

例如想要把字符c和s,替换成k和z,语法如下

>>> a='hello,world!'

>>> table=a.maketrans('l','a')

>>> a.translate(table)

'heaao,worad!'

你可能感兴趣的:(Python)