Python — 操作字元串[3/3]
- 2020 年 1 月 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()一樣,會創建一個新字元串,而不是對字元串進行行內修改。