Learning python学习总结之字符串方法

总结下最近学习lerning python这本书的字符串部分的一些收获吧。

一、原始字符串

在普通字符串前加‘r'即成为原始字符串,特点是抑制转义,即在原始字符串中’\n‘这种转义字符串没有特殊含义了。

二、索引和分片

s = 'abcdefg'

s[1:5:2] = 'ace'

s[5:1:-1] = 'fedc'

s[::-1] = 'gfedcba'

三、字符串转换工具

int('42') = 42

str(42) = '42'

ord('s') = 115

chr(115) = 's'

四、修改字符串

s = 'spam'

s[0] = 'a'  error!!!不能原处修改

s = s + 'hello'

s = s[4:] + ' world' = 'hello world'

五、字符串方法

s = 'hello world'

(1) replace

s.replace( 'o', 'x' ) = 'hellx, wxrld'

(2) join

l = list( s ) = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

' '.join( l ) = 'hello world'

','.join( ['hello', 'world'] ) = 'hello,world'

'spam'.join( ['hello', 'world'] ) = 'hellospamworld'

(3) split

line = 'aaa bbb ccc'

line.split() = ['aaa', 'bbb', 'ccc']   //如果不加任何参数默认用空格来分割

line = 'bob,hacker,40'

line.split( ',' ) = ['bob', 'hacker', '40']

(4) rstrip, lstrip  //分别是去除字符串右端和左端的空白

line = 'the knights who say hi!\n'

line.rstrip() = 'the knights who sya hi!'  //去除行末的空白

(5) endswith, startswith  //rt

(6) find

'hello, world'.find( 'o' ) = 4


你可能感兴趣的:(learning)