字符串是Python中使用非常之多的一种数据结构,它也是一种序列,所以上一篇文章中所讲的关于序列的所有操作也都适用于字符串。不过,因为字符串长度是不可变的,所以分片赋值时需要注意要和字符串的长度相符。字符串的知识主要包括字符串格式化和字符串相关的一些方法。
一,字符串格式化
Python的字符串格式化和C语言是比较像的,使用字符串格式化操作符%来实现。在%的左侧放置一个字符串(格式化字符串),而右侧放置希望格式化的值。例如:
>>> format = "Hello, %s. %s enough for ya?" >>> values = ('world', 'Hot') >>> print format % values Hello, world. Hot enough for ya?
总结一下,字符串基本的转换说明符包括以下几种:
- %字符:标记转换说明符的开始
- 转换标志(可选):-表示左对齐;+表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充。
- 最小字段宽度(可选):转换后的字符串至少应该具有该值指定的宽度。如果是*,那么精度将会从元组中读出。
下面看一些例子:
>>> 'Price of eggs: $%d' % 42 'Price of eggs: $42' >>> 'Hexadecimal price of eggs: %x' % 42 'Hexadecimal price of eggs: 2a' >>> from math import pi >>> 'Pi: %f...' % pi 'Pi: 3.141593...' >>> 'Very inexact estimate of pi: %i' % pi 'Very inexact estimate of pi: 3' >>> 'Using str: %s' % 42L 'Using str: 42' >>> 'Using repr: %r' % 42L 'Using repr: 42L' >>> '%10f' % pi #字段宽度10 ' 3.141593' >>> '%10.2f' % pi #字段宽度10,精度2 ' 3.14' >>> '%.2f' % pi #精度2 '3.14' >>> '%.5s' % 'Guido van Rossum' 'Guido' # 可以使用*作为字段宽度或这精度,此时数值会从元组参数中读出 >>> '%.*s' % (5, 'Guido van Rossum') 'Guido' # 在字段宽度和精度值之前还可以放置一个“标表”,该标表可以时0、+、-或空格。这些标表的作用前面已经有说明 >>> '%010.2f' % pi '0000003.14' >>> '%-10.2f' % pi '3.14 ' >>> print ('% 5d' % 10) + 'n' + ('% 5d' % -10) 10 -10 >>> print ('%+5d' % 10) + 'n' + ('%+5d' % -10) +10 -10
二,字符串方法
1,find
find方法可以在一个较长的字符串中查找子字符串,它返回子串所在位置的最左端索引。如果没有找到则返回-1。该方法还可以接受可选的起始点和结束点参数(但指定范围包括第一个索引,不包括第二个索引,即半闭半开)。
>>> 'With a moo-moo here, and a moo-moo there'.find('moo') 7 >>> 'With a moo-moo here, and a moo-moo there'.find('mooo') -1 >>> subject = '$$$ Get rich now!!! $$$' >>> subject.find('$$$') 0 >>> subject.find('$$$', 1) #只提供起始点 20 >>> subject.find('$$$', 0, 16) #提供起始点和结束点 0
2,join
join时非常重要的字符串方法,它是split方法的逆方法,用来在队列中添加元素(所添加的元素都必须时字符串):
>>> seq = [1, 2, 3, 4, 5] >>> sep = '+' >>> sep.join(seq) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, int found >>> seq = ['1', '2', '3', '4', '5'] >>> sep.join(seq) '1+2+3+4+5' >>> dirs = '', 'usr', 'bin', 'env' >>> dirs ('', 'usr', 'bin', 'env') >>> '/'.join(dirs) '/usr/bin/env' >>> print 'C:' + ''.join(dirs) C:usrbinenv
3,lower
lower方法返回字符串的小写字母版。相反的时upper。
>>> 'Trondheim Hammer Dance'.lower() 'trondheim hammer dance' >>> 'Trondheim Hammer Dance'.upper() 'TRONDHEIM HAMMER DANCE'
4,replace
replace方法返回某字符串的所有匹配项均为替换之后得到的字符串。
>>> 'This is a test'.replace('is', 'eez') 'Theez eez a test'
5,split
该方法时join的逆方法,用来将字符串分割成序列。
>>> '1+2+3+4+5'.split('+') ['1', '2', '3', '4', '5'] >>> '/usr/bin/env'.split('/') ['', 'usr', 'bin', 'env']
6,strip
strip方法返回去除两侧(不包括内部)空格的字符串。
>>> ' internal whitespace is kept '.strip() 'internal whitespace is kept' >>> '*** SPAM * for * everyone!!! ***'.strip(' *!') 'SPAM * for * everyone'
7,translate
translate方法和replace方法一样,可以替换字符串中的某些部分,但是和前者不同的是,translate方法只处理单个字符。它的优势在于可以同时进行多个替换。
>>> from string import maketrans >>> table = maketrans('cs', 'kz') >>> len(table) 256 >>> table[97:123] 'abkdefghijklmnopqrztuvwxyz' >>> maketrans('', '')[97:123] 'abcdefghijklmnopqrstuvwxyz' >>> 'this is an incredible test'.translate(table) 'thiz iz an inkredible tezt'
上例中使用了maketrans函数,该函数用于生成一个长256 bytes的转换表,它接受两个参数:两个等长的字符串,表示第一个字符串中的每个字符都用第二个字符串中相同位置的字符替换。
评论已关闭