# 去除字元串的換行-split
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
new_str=str.split()
print(str)
print(new_str)
','.join(new_str)
-->> Line1-abcdef Line2-abc Line4-abcd ['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] 'Line1-abcdef,Line2-abc,Line4-abcd'
#去除字元串的空格-split
str2='this that hello good'
new_list=str2.split()
print(new_list)
','.join(new_list)
-->> ['this', 'that', 'hello', 'good'] 'this,that,hello,good'Python split()方法 Python 字元串 Python 字元串
描述 Python split() 通過指定分隔符對字元串進行切片,如果參數 num 有指定值,則分隔 num+1 個子字元串
文法 split() 方法文法:
str.split(str="", num=string.count(str)). 參數 str -- 分隔符,預設為所有的空字元,包括空格、換行(\n)、制表符(\t)等。 num -- 分割次數。預設為 -1, 即分隔所有。 傳回值 傳回分割後的字元串清單。
執行個體 以下執行個體展示了 split() 函數的使用方法:
執行個體(Python 2.0+) #!/usr/bin/python
-- coding: UTF-8 --
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"; print str.split( ); # 以空格為分隔符,包含 \n print str.split(' ', 1 ); # 以空格為分隔符,分隔成兩個 以上執行個體輸出結果如下:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']