第03章: 使用字符串
------
支持的操作
- 索引
- 切片
- 增加元素
- 删除元素
- 更新元素
- 查找元素(检查某个元素是否是序列中的一员)
- 序列长度
- 最大值
- 最小值
- 其他内建函数
>>> website='http://www.python.org'
>>> website[-3:]='com' #此操作不合法,因为字符串是不变,不能做修改
Traceback (most recent call last):
File "<pyshell#162>", line 1, in <module>
website[-3:]='com'
TypeError: 'str' object does not support item assignment
------
字符串格式化:
%s:转换说明符 元祖
#字符型
>>> str1 = "Hello, %s. %s enough for you ya?"
>>> val1 = ('Jerry','Hot')
>>> print str1 % val1
Hello, Jerry. Hot enough for you ya?
#浮点型
>>> format = "PI with three decimals: %.3f"
>>> from math import pi
>>> print format % pi
PI with three decimals: 3.142
Note:
1. 使用列表的话,序列会理解成一个值,只有元祖和字典可以格式化一个以上的值
2. 百分号: %%
模板字符串
#类似于linux中的变量替换,Template,substitute(将传的参数进行转换)
>>> s = Template('$x,glorious $x!')
>>> s.substitute(x='slurm')
'slurm,glorious slurm!'
#如果是单词的一部分的话,用{}括起来
>>> s = Template('I love ${x}rry!')
>>> s.substitute(x='She')
'I love Sherry!'
#如果是美元, 注意用$$来表示美元符,safe_substitute不会因缺少值或美元符而报错
>>> s = Template('Using $$ buy ${x}!')
>>> s.substitute(x='food')
'Using $ buy food!'
#利用字典提供键/值对
>>> 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 = Template('I am ${name},${age} years old.')
>>> d = {'name':'Jerry','age':50}
>>> s.substitute(d)
'I am Jerry,50 years old.'
#
>>> s = '%s plus %s equals %s' % (1,1,2)
>>> print s
1 plus 1 equals 2
------
基本的转换说明符号:
(1)%字符,标志转换的开始
(2)转换标志(可选)
- - 左对齐
- + 转换值之前的正负号
- " " 空白字符,表示正数之前,保留空格
- 0 转换值不够,则用0来填充
- 最小具有指定值的宽度
- 如果是*,则值从元祖中读取
- 如果是实数,精度值表示后面的位数
- 如果是字符,精度值表示后面的最大宽度
- 如果是*,精度值从元祖中读取
------
简单转换
>>> print 'price of eggs is %d' % 12
price of eggs is 12
>>> print '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' % 'Hello, world!' #字符串长度
'Hello'
>>> '%.*s' % (5,'Hello,World!')#字符串长度,其值从元祖中读取
'Hello'
------
符号、对齐和0填充
在字段宽度和精度值之前可以放置一个“标表”,可以是0,+," "
>>> '%010.2f' % pi #宽度为10,精度2,不够用0填充
'0000003.14'
>>> 010
8
>>> '%-10.2f' % pi #左对齐
'3.14 '
#空格,在对齐正负数时,会很有用
>>> print ('% 5d' % 10) + '\n' + ('%5d' % -10)
10
-10
#+号,表示不管正数还是负数,标出其正负值,在对齐有用
>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)
+10
-10
字符串格式化示例
width = input('Enter number here:')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
content_format = '%-*s%*.2f'
print '='*width
print header_format % (item_width,'Item',price_width,'Price')
print '-'*width
print content_format % (item_width,'Apples',price_width,0.4)
print content_format % (item_width,'Pears',price_width,0.5)
print content_format % (item_width,'Banana',price_width,8)
print content_format % (item_width,'Tomato',price_width,6)
print '='*width
输出结果:
Enter number here:40
========================================
Item Price
----------------------------------------
Apples 0.40
Pears 0.50
Banana 8.00
Tomato 6.00
========================================
------
字符串方法
find: 在一个长字符串中查找字符,并返回最左边索引位置,第一个位置为0,未找到为:-1
#find 不返回布尔值: -1:未找到 0:找到,索引为0,即开始位置
>>> 'I love python'.find('Perl')
-1
>>> 'I Love Python'.find('Python')
7
>>> title = 'Python is so funny language'
#如果查找的对象在开始位置,则为0
>>> title.find('Python')
0
#如果有多个话,返回第一个匹配的索引值
>>> title.find('o')
4
#该方法可以选择查找的起始点,终结点
>>> subject = '$$$ Get rich now!!! $$$'
#默认的话,从0开始查找
>>> subject.find('$$$')
0
#只提供起始位置
>>> subject.find('$$$',1)
20
#提供了起始位置和终点
>>> subject.find('!!!',0,16)
-1
------
join: split的反方法,用于在队列中添加元素
>>> seq = [1,2,3,4,5] #数字列表
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
File "<pyshell#242>", line 1, in <module>
sep.join(seq)
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' #注意最前面的空格
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print 'C:'+'\\'.join(dirs) #双反斜杠
C:\usr\bin\env
------
lower:将字符串全部转为小写
>>> 'Hello,WORld'.lower()
'hello,world'
#如果在查找的时候,输入是大写则找不到
>>> if 'Jerry' in ['jerry','tom','sherry','john']: print "Found it."
#这时需要先转换为小写
>>> if 'Jerry'.lower() in ['jerry','tom','sherry','john']: print "Found it."
Found it.
#title(): 首字母大写
>>> "This is a dog, that's a pig".title()
"This Is A Dog, That'S A Pig"
#string模块下的capwords()同样可以实现首字母大写功能
>>> import string
>>> string.capwords('hello,world.')
'Hello,world.'
------
replace: 找到后,全部替换
>>> 'Tom and Jerry'.replace('Tom','Sherry')
'Sherry and Jerry'
------
split: 非常重要的方法,join的反方法
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env/python'.split('/')
['', 'usr', 'bin', 'env', 'python']
#如果不提供任何分割符,则以空格,制表格,换行符来分割
>>> 'Using the default'.split()
['Using', 'the', 'default']
------
strip: 除去字符串两侧的空字符,不包括字符串内部
>>> ' How old are you? '.strip()
'How old are you?'
#如果输入可能带空格,则要和strip()结合使用
>>> names = ['jerry','sherry','tom']
>>> name = 'jerry '
>>> if name in names: print 'find it.'
>>> if name.strip() in names: print 'find it.'
find it.
#也可以指定去除的项,如在本地,则是(除掉首微两端的*!)
>>> '***spam * in * everyone!!!***'
'***spam * in * everyone!!!***'
>>> '***spam * in * everyone!!!***'.strip('*!')
'spam * in * everyone'
------
translate: 同replace,可以替换字符串中某些部分。区别,translate只处理单个字符.
优势,可以同时进行多个替换,有些时候比replace效率高.在转换之前需要准备一张转换表
>>> from string import maketrans #和maketrans结合使用
>>> table = maketrans('cs','kz') #用k替换c,用z替换s
>>> 'this is c character'.translate(table)
'thiz iz k kharakter'
------
本章函数
string.capwords(s[,sep]) 使用split函数分割字符串,使用capitalize将分割得到的各单词首字母大写;
并且使join函数以sep为分割符将单词连接起来
string.maketrans(from,to) 创建用于转换的表