今天小編就爲大家分享一篇python實現字符串完美拆分split()的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
函數:split()
例子
我們想要將以下字符串rule進行拆分。字符串表示的是一個規則,由“…”得到“…”。我們需要將規則中的條件屬性與取值分別提取出來,存放在條件屬性列表cf_list與值列表cv_list中,規則的結論的屬性與取值也提取出來,分別存放結果屬性列表rf_list與值列表rc_list。
rule = '{age=Middle-aged,sex=Male,education=Bachelors}=>{native-country=United-States}'
代碼
rule = '{age=Middle-aged,sex=Male,education=Bachelors}=>{native-country=United-States}' c_s, r_s = s.split("=>") c_list = c_s.split("{")[1].split("}")[0].split(",") r = r_s.split("{")[1].split("}")[0] cf_list = [] cv_list = [] for c in c_list: cf, cv = c.split("=") cf_list.append(cf) cv_list.append(cv) rf, rv = r.split("=") print(cf_list, cv_list, rf, rv)
輸出結果:
([‘age', ‘sex', ‘education'], [‘Middle-aged', ‘Male', ‘Bachelors'], ‘native-country', ‘United-States')
部分代碼說明:
1、
c_s, r_s = s.split("=>")
‘=>'爲分隔符,將字符串rule分成兩部分:{age=Middle-aged,sex=Male,education=Bachelors}與{native-country=United-States}
2、
c_list = c_s.split("{")[1].split("}")[0].split(",")
該行代碼將字符串{age=Middle-aged,sex=Male,education=Bachelors}中的{與}濾掉後,將每個條件分開並存儲在列表中。具體地,c_s.split("{")以{將字符串{age=Middle-aged,sex=Male,education=Bachelors}拆分成包含兩個元素的列表['', ‘age=Middle-aged,sex=Male,education=Bachelors}'],第一個元素爲空字符串,不包含任何信息,故只取拆分結果的第二個元素c_s.split("{")[1]。同理,c_s.split("{")[1].split("}")[0]是在之前拆分的基礎上以}對字符串拆分,並濾掉空字符串。
以上這篇python實現字符串完美拆分split()的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持神馬文庫。