Python — 操作字符串[3/3]

 1,splitlines()


yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: multiline_string = """This    ...: is    ...: a multiline    ...: piece of    ...: text"""  In [2]: multiline_string.spli multiline_string.split       multiline_string.splitlines  In [2]: multiline_string.split() Out[2]: ['This', 'is', 'a', 'multiline', 'piece', 'of', 'text']  In [3]: lines = multiline_string.splitlines()  In [4]: lines Out[4]: ['This', 'is', 'a multiline', 'piece of', 'text'] 

糊涂了?仔细看13行和18行的a multilines。

2,join()


yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: some_list = ['one','two','three','four']  In [2]: ','.join(some_list) Out[2]: 'one,two,three,four'  In [3]: 't'.join(some_list) Out[3]: 'onettwotthreetfour'  In [4]: ''.join(some_list) Out[4]: 'onetwothreefour' 

很简单不是吗?

没那么简单,请看:

yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: some_list = range(10)  In [2]: some_list Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  In [6]: ",".join(some_list) --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call last)  /home/yuan/<ipython console> in <module>()  TypeError: sequence item 0: expected string, int found   In [4]: ",".join([str(i) for i in some_list]) Out[4]: '0,1,2,3,4,5,6,7,8,9'  In [5]: ",".join(str(i) for i in some_list) Out[5]: '0,1,2,3,4,5,6,7,8,9' 

很显然join只能处理字符串序列,str()即可。

3,replace()


yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: replacable_string = "trancendental hibernational nation"  In [2]: replacable_string.replace("nation","natty") Out[2]: 'trancendental hibernattyal natty' 

这个没啥好说的,很简单

但是必须说下:replace()和前边说的strip()一样,会创建一个新字符串,而不是对字符串进行行内修改。