2015-11-28 173 views
1

我需要用""(即完全刪除)替換字符串中的任何[key]: null。例如:如何替換鍵+空值,Python

s = 'a: 1, b: null, c: null, d: 0, e: null, f: 0.3' 

與所需的輸出已經b: nullc: nulle: null刪除:

'a: 1, d: 0, f: 0.3' 

其中逗號可以s.replace(', ,','')

被刪除是否有一個乾淨/可靠的方法來做到這一點?當然,鍵名可以改變,但那些值爲null需要刪除。

我想re(正則表達式)包可以有幫助,但我以前沒有用過。

回答

3

您可以使用:

r = re.sub(r'\b\w+:\s+null(,\s*|$)', '', s); 

輸出:

a: 1, d: 0, f: 0.3 

RegEx Demo

+0

或者可能更簡單:re.sub(r「[az]:null,」,「」,s) –

+0

但'a:null'最後也可以像''w:2,a:null' – anubhava

+0

這很整齊。如果分隔符不是'','而是'\ n'?有沒有專門搜索':null'的方法? –

1
s = 'a: 1, b: null, c: null, d: 0, e: null, f: 0.3' 
r='' 
for e in s.split(','): 
    if (e.split(':')[1]!=' null'): 
     r = r+ ',' +e 

print (r[1:]) 
+0

沒有正則表達式,你爲什麼不使用dictonnary? – cutzero

2
s = 'a: 1, b: null, c: null, d: 0, e: null, f: 0.3' 
# split with "," and then ":" 
dataList = [d.strip().split(':') for d in s.split(',')] 
# check if the tuple's second value is string "null" 
dataListFilter = filter(lambda x: x[1].strip() != 'null', dataList) 
# join back the results 
result = ', '.join(map(lambda x: x[0] + ': ' + x[1], dataListFilter)) 
print result 

SUGGESTION: 我建議使用比這種數據類型字符串更好的數據結構。通常哈希(Python字典)適合於如果你有數據控制權。

+0

謝謝。這不是一個數據結構,而是一個YAML轉儲到屏幕上(不需要進一步加載):)現在我需要的只是清理轉儲。可能有一種方法可以用'yaml.representative'去掉'null'鍵,但它仍然在工作中:) –