当前位置:编程学习 > 网站相关 >>

Python的字符串索引和分片

1.字符串的索引

给出一个字符串,可输出任意一个字符,如果索引为负数,就是相当于从后向前数。

[python]
>>> str="HelloWorld!" 
>>> print str[0] 

>>> print str[-4] 

>>> str="HelloWorld!"
>>> print str[0]
H
>>> print str[-4]
r
2.字符串的分片

分片就是从给定的字符串中分离出部分内容。

[python]
>>> str="HelloWorld!" 
>>> print str[0] 

>>> print str[-4] 

>>> print str[1:4] 
ell 
>>> print str[:-7] 
Hell 
>>> print str[5:] 
World! 

>>> str="HelloWorld!"
>>> print str[0]
H
>>> print str[-4]
r
>>> print str[1:4]
ell
>>> print str[:-7]
Hell
>>> print str[5:]
World!
分片的扩展形式:

str[I,J,K]意思是从I到J-1,每隔K个元素索引一次,如果K为负数,就是按从由往左索引。

[python]
>>> print str[2:7:2] 
loo 
>>> print str[2:7:1] 
lloWo 

>>> print str[2:7:2]
loo
>>> print str[2:7:1]
lloWo
ord函数是将字符转化为对应的ASCII码值,而chr函数是将数字转化为字符。例如:

[python]
>>> print ord('a') 
97 
>>> print chr(97) 

>>>  

>>> print ord('a')
97
>>> print chr(97)
a
>>> 

Python中修改字符串只能重新赋值。

每修改一次字符串就生成一个新的字符串对象,这看起来好像会造成效率下降,其实,在Python内部会自动对不再使用的字符串进行垃圾回收,所

以,新的对象重用了前面已有字符串的空间。

 

字符串格式化:

[python]
>>> "%d %s %d you!"%(1,"goujinping",8) 
'1 goujinping 8 you!' 

>>> "%d %s %d you!"%(1,"goujinping",8)
'1 goujinping 8 you!'

 

补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,