python3 字符串属性(四)

1、

S.partition(sep) -> (head, sep, tail)

Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.

分割作用,参数为分割字符,分为三部分,(参数前,参数,参数后);如果参数没有找到,返回原字符串和两个空字符串。参数有多个,以第一个为准。S.partition(sep) -> (head, sep, tail)   以最后一个参数为准。

 

 1 >>> a
 2 'acbsdwf124'
 3 >>> a.partition('d')
 4 ('acbs', 'd', 'wf124')
 5 >>> a.partition('i')
 6 ('acbsdwf124', '', '')
 7 >>> a.partition('sd')
 8 ('acb', 'sd', 'wf124')
 9 >>> a='hello world hello huhu !'
10 >>> a.partition('hello')
11 ('', 'hello', ' world hello huhu !')

 

2、

S.replace(old, new[, count]) -> str

Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.

替换

1 >>> a='1a2a3a4a5a'
2 >>> a.replace('a','b')
3 '1b2b3b4b5b
4 >>> a.replace('a','b',3)
5 '0b1b2b3a4a5a    #替换前三个

 

3、

S.split(sep=None, maxsplit=-1) -> list of strings

Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.

S.rsplit(sep=None, maxsplit=-1) -> list of strings  第二个参数,从右侧开始划分。

文本解析,默认为空格,空格将被移除。返回字符串列表。

 1 >>> a='hello world ,huhu !'
 2 >>> a.split()
 3 ['hello', 'world', ',huhu', '!']
 4 >>> a.split(',')
 5 ['hello world ', 'huhu !']
 6 >>> a='hello:world:huhu'
 7 >>> a.split(':',2)
 8 ['hello', 'world', 'huhu']
 9 >>> a.split(':',1)
10 ['hello', 'world:huhu']  #从左侧划分。

S.splitlines([keepends]) -> list of strings

Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true

1 >>> a="""hello world!
2 ... second line
3 ... splitlins test
4 ... """
5 >>> a.splitlines()
6 ['hello world!', 'second line', 'splitlins test']
7 >>> a.splitlines(True) #保留行分割符
8 ['hello world!\n', 'second line\n', 'splitlins test\n']

 

4、

S.swapcase() -> str

Return a copy of S with uppercase characters converted to lowercase
and vice versa.

字母大小写转换

1 >>> a='ABCDefgh'
2 >>> a.swapcase()
3 'abcdEFGH'

 

5、

S.zfill(width) -> str

Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.

 

给定长度,左侧添零补充

1 >>> a
2 'ABCDefgh'
3 >>> a.zfill(10)
4 '00ABCDefgh'

 

posted @ 2016-03-11 21:39  hb91  阅读(532)  评论(0编辑  收藏  举报