python3.2.2中使用字符串

三、使用字符串
#1。基本字符串操作
跟序列类似,索引、分片、加、乘、判断成员资格、求长度、取最大、取最小。
字符串不可变
#2。字符串格式化
用%来实现。
%也是取模运算符号。

>>> format='hello,%s.%s enough for ya?'
>>> values=('world','hot')
>>> print(format%values)
hello,world.hot enough for ya?

以上的代码中不能用序列而使用元组,如果用序列会返回一个值。
格式化字符串%s部分称为转换说明符(conversion specifier),它们标记了需要插入转换值的位置。s表示值会格式化为字符----如果不是字符串会用str转换为字符串。
要格式化实数,用f说明符类型。

>>> fomat='pi with three decimal:%.3f'
>>> from math import pi
>>> print(fomat%pi)
pi with three decimal:3.142

##模板字符串
string提供另外一种字符串格式化方法:模版字符串。
substitute这个模板方法用传递进来的关键字参数foo替换字符串中$foo

>>> from string import Template
>>> s=
SyntaxError: invalid syntax
>>> s=Template('$x,glorious $x!')
>>> s
<string.Template object at 0x02F77BD0>
>>> s.substitute
<bound method Template.substitute of <string.Template object at 0x02F77BD0>>
>>> s.substitute(x='slurm')
'slurm,glorious slurm!'
>>> s
<string.Template object at 0x02F77BD0>
>>> y=s.substitute(x='slurm')
>>> y
'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.'
>>> 

#3。字符串格式化:完成版
(1)%标记转换说明符的开始
(2)转换标志(可选):-左对齐;+表示转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换位数不够用0填充。
(3)最小字段宽度(可选):转换后的字符应该有该值指定的宽度。如果**,则宽度从元组中读取。
(4)点(.)后跟精度值(可选):如果转换的实数,精度值表示小数点后的位数。如果转换字符串,表示最大字段宽度。如果**,精度从元组中读取。
(5)转换类型

#使用给定的宽度打印格式化后的价格列表
width=int(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,'Cantaloupes',price_width,1.92))
print(format%(item_width,'Dried Apricot(16 oz.)',price_width,8))
print(format%(item_width,'Prunes(4 lbs.)',price_width,12))
print('='*width)
#运行结果
>>> 
Please enter width: 20
====================
Item           Price
--------------------
Apples          0.40
Pears           0.50
Cantaloupes      1.92
Dried Apricot(16 oz.)      8.00
Prunes(4 lbs.)     12.00
====================

#4。字符串方法
##1)find
在较长字符串中查找子字符串,返回子字符串最左端的索引值。如果没有返回-1。

>>> title="Monty Python's Flying Cirus"
>>> title.find('Monty')
0

##2)join
是split的逆方法,在队列中添加元素。
添加的元素必须是字符串。

>>> dirs=['','usr','bin','env']
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('C:'+'\\'.join(dirs))
C:\usr\bin\env

##3)lower
返回字符串的小写子母版。

>>> name='Gumby'
>>> names=['gumby','smith','jones']
>>> if name.lower() in names :print('Found it!')
SyntaxError: invalid character in identifier
>>> if name.lower() in names :print('Found it!')
SyntaxError: invalid character in identifier
>>> if name.lower() in names :print('found it!')
SyntaxError: invalid character in identifier
>>> if name.lower() in names :print('in')
SyntaxError: invalid character in identifier
>>>  if name.lower() in names :print("Found it!")
 
SyntaxError: unexpected indent
>>> if name.lower() in names :print("Found it!")
SyntaxError: invalid character in identifier
>>> if name.lower() in names:print('Found it!')

Found it!

##4)replace
返回字符串中的所有匹配项均被替换之后得到的字符串。

>>> 'This is a test'.replace('is','are')
'Thare are a test'
>>> 

##5)split
join的逆方法,将字符串分割成序列。

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

##6)strip
返回去除两侧空格(不包括内部的)的字符串。也可以指定需要去除的字符。

>>> names=['gumby','smith','jones']
>>> name='Gumby   '
>>> if name.lower() in names:print('Found it!')

>>> if name.strip() in names:print('Found it!')

>>> if name.lower().strip() in names:print('Found it!')

Found it!
>>> '****   SPAM*for*everyone!!!****'.strip(' *!')
'SPAM*for*everyone'
>>> 

##7)translate
和replace方法一样,不同之处在于translate只处理单个字符。优势可同时做多个替换。效率比replace高。
在使用translate之前要做转换表,转换表中有需要替换的字符与字符之间的对应关系。这个表可以用string模块中的maketrans函数实现。

>>> table=str.maketrans('cs','kz')
>>> len(table)
2
>>> table
{115: 122, 99: 107}
>>> table[97:123]
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    table[97:123]
TypeError: unhashable type: 'slice'
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
>>> 'this is an incredible test'.translate(table,' ')
Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    'this is an incredible test'.translate(table,' ')
TypeError: translate() takes exactly one argument (2 given)
>>> 'this is an incredible test'.translate(table).del(' ')
SyntaxError: invalid syntax
>>> 'this is an incredible test'.translate(table).replace(' ','')
'thizizaninkredibletezt'
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值