python基础教程学习笔记 第三章 字符串

来源:互联网 发布:古剑奇谭ol 知乎 编辑:程序博客网 时间:2024/05/17 22:02
基本字符串操作
所有标准的序列操作:索引,分片,乘法,判断成员资格,求长度,取最小值和最大值,对字符串同样适用。
字符串是不可变的。

字符串格式化:精简版
 格式化字符串 % 希望格式化的值
>>> f="Hello,%s,%s enough for ya?"
>>> values=('d','w')
>>> print f %values
Hello,d,w enough for ya?
>>> values=[1,2]
>>> print f % values
如果使用列表或者其他序列代替元组,那么序列就会被解释为一个值。只有元组和字典可以格式化一个以上的值。
%s 转换说明符 s 表示值会被格式化为字符串
通过格式化字符串中有百分号,必须用%%
格式化实数(浮点数),
>>> format='Pi with three decimals:%.3f'
>>> from math import pi
>>> print format % pi
Pi with three decimals:3.142
模板字符串
>>> from string import Template>>> s=Template('$x,glorious $x!')>>> s.substitute(x='slurm')#传递进来的关键字参数x替换$x'slurm,glorious slurm!'>>> s=Template("It's ${x}tastic!")#替换字段是单词的一部分,那么参数名必须用括号括起来>>> s.substitute(x='slurm')"It's slurmtastic!">>> s=Template('Make $$ selling $x!')#用$$插入美元符号>>> s.substitute(x='slurm')'Make $ selling slurm!'>>> 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'


方法safe_substitute不会因缺少值或者不正确使用$字符而出错。

字符串格式化:完整版
格式化字符串% 希望格式化的值--可以是任何东西,元组或者映射类型
>>> '%s plus %s equals %s' % (1,2,3)
'1 plus 2 equals 3'
%字符:标记转换说明符的开始
转换标志(可选):-表示左对齐,+表示在转换值之前要加上正负号;""(空白字符)表示正数自谦保留空格,0表示转换值若位数不够则用0填充。
最小字段宽度(可选):转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度会从值元组中读出。
点(.)后跟精度值(可选):如果转换是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将会从元组中读出。

d,i 带符号的十进制   u 不带符号的十进制
o 不带符号的八进制     x 不带符号的十六进制(小写)
X不带符号的十六进制(大写) e 科学计数法表示的浮点数(小写)
E 科学计数法表示的浮点数(大写) f,F 十进制浮点数
g 如果指数大于-4或者精度值则和e相同,其他情况与f相同
G 如果指数大于-4或者小鱼精度值则和E相同,其他情况与F相同
C 单字符(接受整数或者单字符字符串)
r 字符串(使用repr转换任意python对象)
s 字符串(使用str转换任意python对象)
>>> "Price of eggs:$%d" % 42
'Price of eggs:$42'
>>> "Hexadecimal price of eggs: %x" % 42
'Hexadecimal price of eggs: 2a'
>>> "Hexadecimal price of eggs: %X" % 42
'Hexadecimal price of eggs: 2A'
>>> from math import pi
>>> "Pi: %f..." % pi
'Pi: 3.141593...'
>>> "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'
>>> "%4f" %pi
'3.141593'
>>> "%4.2f" %pi #字段宽4 精度2
'3.14'
>>> "%.2f" %pi #精度2
'3.14'
>>> "%.5s" % "Guido van Rossum" #字段长度为5
'Guido'
>>> "%10.5s" % "Guido van Rossum" #字段宽度10 长度5
' Guido'
>>> '%.*s'% (5,"Guido van Rossum") # * 数值会从元组参数中读出
'Guido'

符号,对齐 和 0填充
>>> "%010.2f" % pi # 字段宽度为10,并且用0进行填充空位
'0000003.14'
>>> "%-10.2f" %pi # -左对齐
'3.14   '
>>> print ('% 5d' % 10) +'\n'+('% 5d' % -10)
  10
  -10
>>> print('%+5d' %10)+'\n'+('%+5d' % -10)# +表示不管是正数还是负数都标示出符号
  +10
  -10
eg:
format.py
width=input("Please enter width:")
price_width=10
item_width=width-price_width

header_format='%-*s%*s'
format ='%-*s%*.2f'
print "="*width

print header_format %(item_width,'Item',price_width,"Price")
print '-'*width

print format %(item_width,"Apples",price_width,0.4)
print format % (item_width,"Pears",price_width,0.5)
print format %(item_width,"Caqntaloupes",price_width,1.92)

print "=" * width
run:
>>>
===================== RESTART: E:/pythonlearn/format.py =====================
Please enter width:35
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Caqntaloupes                   1.92
===================================
>>>

字符串方法 
字符串方法完全来源于string模块,但是一些不能作为字符串方法使用
>>> import string
>>> string.digits 包含数字0-9的字符串
'0123456789'
>>> string.letters 包含所有字母(大小写)的字符串
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.lowercase 包含所有小写字母的字符串
'abcdefghijklmnopqrstuvwxyz'
>>> string.printable 包含所有可打印字符的字符串
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.punctuation 包含所有标点的字符串
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.uppercase 包含所有大写字母的字符串
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

字母字符串常量与地区有关,如果可以确定自己使用的是ascii,那么可以在变量中使用ascii_前缀,string.ascii_letters

1find
find 方法可以在一个较长的字符串中查找子字符串,他返回紫川所在位置的最左端索引。
>>> "With a moo-moo here. and a moo-moo there.".find('moo')
7
>>> title="Monty python's Flying Circus"
>>> title.find("Monty")
0

字符串的find 方法并不是返回布尔值,如果返回的是0,则证明索引0位置找到了子串
还可以接受可选的起始点和结束点参数:
>>> subject="$$ Get rich now!!! $$">>> subject.find("$$")0>>> subject.find('$$',1)20>>> subject.find('!!!')16>>> subject.find('!!!',0,16) #包括第一个索引,但不包括第二个索引-1
2.join
split方法的逆方法
需要添加的对垒元素必须要是字符串。
>>> seq=[1,2,3,4,5]
>>> sep='+'
>>> sep.join(seq)

Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
  sep.join(seq)
TypeError: sequence item 0: expected string, int found
>>> seq=['1','3','3','5','6']
>>> sep.join(seq)
'1+3+3+5+6'
>>> dirs='','usr','bin','env'
>>> "/".join(dirs)
'/usr/bin/env'
>>> print "c:"+"\\".join(dirs)
c:\usr\bin\env

3.lower
islower,capitalize,swapcase,title,istitle, upper,isupper
>>> "Trondheim Hammer Dance".lower()
'trondheim hammer dance'
>>> name ="Gumby"
>>> names=["gumby",'smith','jones']
>>> if name.lower() in names:print "Found it!"

Found it!
>>> "that's all folks".title()#将字符串转换成标题
"That'S All Folks"
>>> import string
>>> string.capwords("that's all ,folks")#首字母大写的标题
"That's All ,folks"

4.replace
返回某字符串的所有匹配项均被替换之后得到的字符串
>>> "This is a test".replace('is','eez')
'Theez eez a test'

5.split
>>> "1+2+3+4".split("+")
['1', '2', '3', '4']

6.strip
去除两端空白
>>> ' interna, whitespace is kept '.strip()
'interna, whitespace is kept'
>>> '*** spam * for * everyone!!!***'.strip("*!")#去除两端的字符
' spam * for * everyone'
>>> '*** spam * for * everyone!!!***'.strip("!")
'*** spam * for * everyone!!!***'
>>> '*** spam * for * everyone!!!***'.strip("*")
' spam * for * everyone!!!'

7.translate
只处理单个字符,同时进行多个替换
>>> from string import maketrans #转换表
>>> table=maketrans('cs','kz')#定义转换规则 c换成k,s换成z
>>> len(table)#转换表包含替换Ascii字符集中256个字符的替换字母的字符串
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz'
>>> maketrans('','')[97:123]
'abcdefghijklmnopqrstuvwxyz'
>>> "this is an incredible test".translate(table)
'thiz iz an inkredible tezt'
>>> "this is an incredible test".translate(table,' ')#第二个参数,需要删除的字符
'thizizaninkredibletezt'

遇到非英文字母的字母,可以通过translate进行转换

字符串格式化:求模操作符(%)可以用来将其他值转换为包含转换标志的字符串
左右对齐,设置字段宽度以及精度值,增加符号(正负号)或者左填充数字0等
字符串方法:

新函数
string.capwords(s[,seq]) 使用split函数分割字符串s(以seq为分隔符),使用capitalize函数将分割得到的个单词首字母大写,并且使用join函数以seq问分隔符将各单词连接起来
>>> string.capwords("that's all ,folks")#首字母大写的标题
"That's All ,folks"

string.maketrans(from,to) 创建用于转换的转换表






1 0
原创粉丝点击