龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

Python入门篇之字符串(2)

时间:2014-10-18 12:09来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: s='spam' s[0],s[-2] ('s', 'a') s[1:3],s[1:],s[:-1] ('pa', 'pam', 'spa') s[0],s[-2] ('s', 'a') 扩展分片:第三个限制值 分片表达式增加了一个可选的第三个

复制代码 代码如下:

>>> s='spam'
>>> s[0],s[-2]
('s', 'a')
>>> s[1:3],s[1:],s[:-1]
('pa', 'pam', 'spa')
>>> s[0],s[-2]
('s', 'a')

扩展分片:第三个限制值

分片表达式增加了一个可选的第三个索引,用作步进X[I:J:K]表示:索引X对象中的元素,从偏移为I直到偏移为J-1,每隔K元素索引一次

复制代码 代码如下:

>>> s='abcdefghijklmnop'
>>> s[1:10:2]
'bdfhj'
>>> s[::2]
'acegikmo'
>>> s='hello'
>>> s[::-1]
'olleh'
>>> s[4:1:-1]
'oll'

字符串转换工具

复制代码 代码如下:

>>> '42'+1
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    '42'+1
TypeError: cannot concatenate 'str' and 'int' objects
>>> int('42'),str(42)
(42, '42')
>>> repr(42),'42'
('42', '42')
>>> s='42'
>>> i=1
>>> s+i
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    s+i
TypeError: cannot concatenate 'str' and 'int' objects
>>> int(s)+i
43
>>> s+str(i)
'421'
>>> #类似也可以把浮点数转换成字符串或把字符串转换成浮点数
>>> str(3.1415),float("1.3")
('3.1415', 1.3)
>>> text='1.23E-10'
>>> float(text)
1.23e-10

字符串代码转换

单个字符也可以通过将其传给内置的ord函数转换为其对应的ASCII码,chr函数则执行相反的操作:

复制代码 代码如下:

>>> ord('s')
115
>>> chr(115)
's'

字符串方法

字符串比列表的方法还要丰富很多,因为字符串从string模块中“继承”了很多方法,本篇文章只介绍一些特别有用的字符串方法

 1、find

find方法可以在一个较长的字符串中查找一个子字符串,它返回子串所在位置的最左端索引,如果没有找到则返回-1

复制代码 代码如下:

>>> 'with a moo-moo here, and a moo-moo there'.find('moo')
7
>>> title="Monty Python's Flying Cirus"
>>> title.find('Monty')
0
>>> title.find('Python')
6
>>> title.find('Zirquss')
-1

这个方法可以接受可选的起始点和结束点参数:

复制代码 代码如下:

>>> subject='$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$',1)
20
>>> subject.find('!!!')
16
>>> subject.find('!!!',0,16)
-1

2、join

join方法是非常重要的字符串方法,它是split方法的逆方法,用来在队列中添加元素:

复制代码 代码如下:

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

Traceback (most recent call last):
  File "<pyshell#15>", 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

3、lower

lower方法返回字符串的小写字母版

精彩图集

赞助商链接