Python入门篇之字符串(2)
>>> 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方法返回字符串的小写字母版
- 上一篇:Python入门篇之字典
- 下一篇:Python入门篇之列表和元组






