第3章 使用字符串

第3章 使用字符串;

format="Hello,  %s,%s enough for ya?"
values=('world','hot')
print format % values

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
Hello,  world,hot enough for ya?

Process finished with exit code 0


format="Hello,  %s,%s,%%s enough for ya?"
values=('world','hot')
print format % values

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
Hello,  world,hot,%s enough for ya?

Process finished with exit code 0



format="Pi wit three decimals:%.5f"
from math import pi
print format %  pi


format="Pi wit three decimals:%.5f"

print format %  3.2555455454

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
Pi wit three decimals:3.25555

Process finished with exit code 0

如果要格式化实数(浮点数),可以使用f说明类型,同样提供所需要的精度:


一个句点在加上希望保留的小数位数。


substitute 变量替换:

from string import Template
s=Template('$x,glorious $x!')
print s.substitute(x='slurm')

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
slurm,glorious slurm!

如果替换字段是单词的一部分,那么参数名就必须用括号括起来,从而准确指明结尾:

from string import Template
s=Template("It's ${x}tastic!")
print s.substitute(x='slurm')

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
It's slurmtastic!


3.3 字符串格式化:完整版:

>>> '%s plus %s equals %s' %(1,2,3)
'1 plus 2 equals 3'

(1) %字符:标记转换说明符的开始

 (2)  转换标志


3.4 字符串方法:


3.4.1  find 方法:


find 方法可以在一个较长的字符串中查找字符串,它返回子串所在的位置的最左端索引。

如果没有找到则返回-1

title="Money Python's Flying Circus"
print title.find('Money');


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
0



3.4.2 join方法:

seq=['1','2','3','4','5']
sep='+'
print sep.join(seq)

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
1+2+3+4+5

3.4.3  lower:


print 'Trondheim Hammer Dance'.lower()

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
trondheim hammer dance

3.4.4  replace


x='this is a test'

print x.replace('is','eez')

3.4.5 split:

这是一个非常重要的字符串方法,它是join的逆方法,用来将字符串分隔成序列


x='1,2,3,4,5'
print x.split('+')


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
['1,2,3,4,5']


3.4.6 strip:

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

x='  dadad'
print x.strip()


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
dadad

注意:/*********字符串也是一个对象















posted @ 2016-07-26 12:47  czcb  阅读(135)  评论(0编辑  收藏  举报