python基础教程_学习笔记5:字符串


字符串

基本字符串操作

字符串也是序列,因此序列的基本操作(索引、分片、连接、乘法、长度、求最大值和最小值、成员资格)对字符串同样适用:

索引

>>> 'a_string'[0]

'a'

长度

>>> len('a_string')

8

求最大值

>>> max('a_string')

't'

求最小值

>>> min('a_string')

'_'

乘法

>>> 'a_string'*2

'a_stringa_string'

连接

>>> 'a_string'+'another_string'

'a_stringanother_string'

分片

>>> 'a_string'[2:6]

'stri'

>>> 'a_string'[1:7:3]

'_r'

赋值

>>> 'a_string'[3]='b'

Traceback (most recent call last):

File "", line 1, in

TypeError: 'str' object does not support item assignment

因为字符串是不可修改的,因此,赋值操作对字符串不可用。

字符串格式化

字符串格式化使用字符串格式化操作符,即百分号%来实现。

在%的左侧放置一个字符串(格式化字符串),而右侧则放置希望格式化的值。可以使用一个值,如一个字符串或者数字:

>>> print "Hello,%s!" %'signjing'

Hello,signjing!

>>> age=20

>>> print "I'm %d years old!" %age

I'm 20 years old!

也可以使用多个值的元组或者字典。一般情况下使用元组:

>>> format="Hello,%s,%s enough for ya?"

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

>>> print format % values

Hello,world,Hot enough for ya?

如果使用列表或者其他序列代替元组,序列会被解释为一个值。只有元组和字典可以格式化一个以上的值。

格式化字符串的%s部分称为转换说明符,它们标记了需要插入转换值的位置。s表示值会被格式化为字符串——如果不是字符串,则会用str将其转换为字符串。这个方法对大多数值都有效。

如果要在格式化字符串里面包括百分号,那么必须使用%%,指引python就不会将百分号误认为是转换说明符了。

>>> print "%s %s" %'test'

Traceback (most recent call last):

File "", line 1, in

TypeError: not enough arguments for format string

>>> print "%s %%s" %'test'

test %s

>>> print "%%s %s" %'test'

%s test

如果要格式化实数(浮点数),可以使用f说明符类型,同时提供所需要的精度:一个句点再加上希望保留的小数位数。因为格式化说明符总是以表示类型的字符结束,所以精度应该放在类型字符前面:

>>> print "PI is %.2f" %3.1415926

PI is 3.14

格式化操作符的右操作数可以是任何东西,如果是元组或者映射类型(如字典),那么字符串格式化将会有所不同。

如果右操作数是元组的话,其中的每一个元素都会被单独格式化,每个值都需要一个对应的转换说明符。如果需要转换的元组作为转换表达式的一部分存在,那么必须将它用圆括号括起来,以免出错:

正确

>>> '%s plus %s is %s' %(12,3,4)

'12 plus 3 is 4'

错误

>>> '%s plus %s is %s' %12,%3,%4

File "", line 1

'%s plus %s is %s' %12,%3,%4

^

SyntaxError: invalid syntax

>>> '%s plus %s is %s' %12 %3 %4

Traceback (most recent call last):

File "", line 1, in

TypeError: not enough arguments for format string

>>> '%s plus %s is %s' %12 %3 %4

Traceback (most recent call last):

File "", line 1, in

TypeError: not enough arguments for format string

基本的转换说明符

基本的转换说明符(不包括映射键的说明符)包括如下[这些项的顺序是至关重要的]:

%[转换标志][最小字段宽度][.精度值]转换类型

%字符:

标记转换说明符的开始

转换标志(可选):

-表示左对齐;

+表示在转换值之前要加上正负号;

””(空白字符)表示正数之前保留空格;

0表示转换值若位数不够则用0填充;

最小字段宽度(可选):

转换后的字符串至少应该具有该值指定的宽度。

如果是*,则宽度会从值元组中读出。

点(.)后跟精度值(可选):

如果转换的是实数,精度值就表示出现在小数点后的位数。

如果转换的是字符串,那么该数字就表示最大字段宽度。

如果是*,那么精度将会从元组中读出。

转换类型:见下表;

字符串格式化转换类型

转换类型 含义

d,i 带符号的十进制整数

o 不带符号的八进制

u 不带符号的十进制

x 不带符号的十六进制(小写)

X 不带符号的十六进制(大写)

e 科学计数法表示的浮点数(小写)

E 科学计数法表示的浮点数(大写)

f,F 十进制浮点数

g 如果指数大于-4或者小于精度值则和e相同,其它情况与f相同

G 如果指数大于-4或者小于精度值则和E相同,其它情况与F相同

c 单字符(接受整数或者单字符字符串)

r 字符串(使用repr转换任意python对象)

s 字符串(使用str转换任意python对象)

简单转换

带符号的十进制整数

>>> "Price is $%d" %42

'Price is $42'

>>> "Price is $%i" %42

'Price is $42'

不带符号的八进制

>>> "number is %o" %42

'number is 52'

不带符号的十进制

>>> "number is %u" %100

'number is 100'

不带符号的十六进制(大写)

>>> 'number is %X' %155

'number is 9B'

不带符号的十六进制(小写)

>>> 'number is %x' %155

'number is 9b'

科学计数法表示的浮点数(小写)

>>> 'number is %e' %155

'number is 1.550000e+02'

科学计数法表示的浮点数(大写)

>>> 'number is %E' %155

'number is 1.550000E+02'

十进制浮点数

>>> 'number is %f' %155

'number is 155.000000'

>>> 'number is %F' %155

'number is 155.000000'

如果指数大于-4或者小于精度值则和E相同,其它情况与F相同

>>> 'number is %G' %0.000000126

'number is 1.26E-07'

>>> 'number is %g' %0.000000126

'number is 1.26e-07'

>>> 'number is %G' %126

'number is 126'

>>> 'number is %g' %126

'number is 126'

>>> 'number is %g' %1260000000000

'number is 1.26e+12'

>>> 'number is %G' %1260000000000

'number is 1.26E+12'

单字符(接受整数(0~255)或者单字符字符串)

>>> 'number is %c' %123

'number is {'

>>> 'number is %c' %'b'

'number is b'

>>> 'number is %c' %255

'number is \xff'

>>> 'number is %c' %256

Traceback (most recent call last):

File "", line 1, in

OverflowError: unsigned byte integer is greater than maximum

>>> 'number is %c' %0

'number is \x00'

>>> 'number is %c' %-1

Traceback (most recent call last):

File "", line 1, in

OverflowError: unsigned byte integer is less than minimum

字符串(使用str转换任意python对象)

>>> 'Using str:%s' %12L

'Using str:12'

字符串(使用repr转换任意python对象)

>>> 'Using repr:%r' %12L

'Using repr:12L'

字段宽度和精度

转换说明符可以包括字符宽度和精度。

字符宽度:

是转换后的值所保留的最小字符个数,

精度:

(对于数字来说)则是结果中应该包含的小数位数;

(对于字符串转换来说)是转换后的值所包含的最大字符个数;

这两个参数都是整数(首先是字符宽度,然后是精度),通过点号(.)分隔。虽然两个都是可选的参数,但如果只给出精度,就必须包含点号:

>>> from math import pi

>>> '%10f' %pi

' 3.141593'

>>> '%10.2f' %pi

' 3.14'

>>> '%.2f' %pi

'3.14'

>>> '%.5s' % 'Signjing'

'Signj'

可以使用*(星号)作为字段宽度或者精度(或者两者都使用*),此时数值会从元组参数中读出:

>>> '%.*s' % (5,"signjing")

'signj'

>>> '%.*s' % (7,"signjing")

'signjin'

符号、对齐和0填充

在字段宽度和精度值之前还可以放置一个“标表”,该标表可以是零、加号、减号或空格。零表示数字将会用0进行填充。

>>> '%10.2f' %pi

' 3.14'

>>> '%010.2f' %pi

'0000003.14'

>>> '%+010.2f' %pi

'+000003.14'

>>> '%-010.2f' %pi

'3.14 '

>>> '% 10.2f' %pi

' 3.14'

注意:

在010中开头的那个0并不意味着字段宽度说明符为八进制,它只是个普通的python数值。

当使用010作为字符宽度说明符的时候,表示字段宽度为10,并且用0进行填充空位,而不是说字段宽度为8:

>>> 010

8

减号(-)用来左对齐数值:

空白(“”)意味着在正数前加上空格,这在需要对齐正负数时会很用。

>>> '% .2f' %pi

' 3.14'

>>> '% .2f' %-pi

'-3.14'

加号(+),表示不管是正数还是负数都标示出符号(同样是在对齐时很有用):

>>> print ('%+5d' %10)+'\n'+('%+5d' % -10)

+10

-10

字符串方法

字符串方法太多,此处只列举几个比较有用的。

find

find方法可以在一个较长的字符串中查找子字符串,返回子串所在位置的最左端索引,如果没有找到则返回-1(与列表或元组的index方法找不到时则返回错误)。

>>> 'I\'m a sunny boy'.find('sun')

6

>>> 'I\'m a sunny boy'.find('sunb')

-1

find方法还可以接受可选的起始点和结束点参数:

只提供起始点:

>>> 'I\'m a sunny boy'.find('sun',5)

6

>>> 'I\'m a sunny boy'.find('sun',9)

-1

提供起始点和结束点

>>> 'I\'m a sunny boy'.find('sun',5,7)

-1

>>> 'I\'m a sunny boy'.find('sun',5,9)

6

记住,就像列表的分片操作一样,find方法的第2和第3个参数,包含第二个参数的索引值,但不包括第3个参数的索引值,这是python中的一个惯例。

>>> 'I\'m a sunny boy'.find('sun',6,9)

6

>>> 'I\'m a sunny boy'.find('sun',6,8)

-1

join(非常重要)

join方法是非常重要的字符串方法,它是split方法的逆方法,用来在队列中添加元素:

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

>>> sep='+'

>>> sep.join(seq)

Traceback (most recent call last):

File "", line 1, in

TypeError: sequence item 0: expected string, int found

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

>>> sep='+'

>>> sep.join(seq)

'1+2+3+4+5'

可见,需要添加的队列元素都必须是字符串。

lower

lower方法返回字符串的小写字母版:

>>> "Signjing".lower()

'signjing'

>>> "signjing".lower()

'signjing'

如果想编写“不区分大小写”的代码的话,该方法就派上用场了。

replace

replace方法返回某字符串的所有匹配项均被替换之后得到字符串。

>>> "Signjing".replace("Si","fin")

'fingnjing'

>>> "This is a test".replace("is","eez")

'Theez eez a test'

split(非常重要)

它是join的逆方法,用来将字符串分割为序列。

>>> 'id,index,name,info'.split(',')

['id', 'index', 'name', 'info']

如果不提供任何分隔符,程序会把所有空格作为分割符(空格、制表、换行等)。

>>> 'id index name info'.split()

['id', 'index', 'name', 'info']

>>> 'id index name info'.split()

['id', 'index', 'name', 'info']

strip

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

>>> " space space ".strip()

'space space'

strip方法和lower方法一起使用可以很方便地对比输入的和存储的值。

也可以指定需要去除的字符:

>>> 'space space'.strip('e')

'space spac'

>>> 'space space'.strip('se')

'pace spac'

translate

translate方法和replace方法一样,可以替换字符串中的某些部分,但和后者不同的是,translate方法只处理单个字符。它的优势在于可以同时进行多个替换,有些时候比replace效率高得多。

在使用translate转换之前,需要先完成一张转换表。转换表中是以字符替换某字符的对应关系。因为这个表(事实上是字符串)有多达256个项目,可以直接使用string模块里面的maketrans函数。

maketrans函数接受两个参数:两个等长的字符串,表示第一个字符串中的每个字符都用第二个字符串中相同位置的字符替换。

>>> from string import maketrans

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

>>> len(table)

256

>>> table

'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abkdefghijklmnopqrztuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'

>>> table[97:123]

'abkdefghijklmnopqrztuvwxyz'

>>> maketrans('','')[97:123]

'abcdefghijklmnopqrstuvwxyz'

>>> maketrans('cs','kz')[97:123]

'abkdefghijklmnopqrztuvwxyz'

创建这个表后,可以用作translate方法的参数,进行字符串的转换如下:

>>> 'this is an incredible test'.translate(table)

'thiz iz an inkredible tezt'

第二个参数可选,用来指定需要删除的字符:

>>> 'this is an incredible test'.translate(table,' ')

'thizizaninkredibletezt'

>>> 'this is an incredible test'.translate(table,'thi')

'z z an nkredble ez'

评论关闭