2014-02-07 205 views
3

我有我的數據如下Python - 如何在分割字符串時忽略雙引號中的空格?

string = ' streptococcus 7120 "File being analysed" rd873 ' 

我試圖拆使用n=string.split()這給下面的結果行:

[streptococcus,7120,File,being,analysed,rd873] 

我想拆分字符串忽略空格「」

# output expected : 

[streptococcus,7120,File being analysed,rd873] 
+0

是否有可能嵌套引號(例如'「文件名」foo「被分析爲」')? – senshin

+0

另請參閱[this](http://stackoverflow.com/questions/2785755/how-to-split-but-ignore-separators-in-quoted-strings-in-python)。 – devnull

回答

4

使用re.findall與合適的正則表達式。我不確定你的錯誤情況是什麼樣子(如果有奇數的引號?),但是:

filter(None, it.chain(*re.findall(r'"([^"]*?)"|(\S+)', ' streptococcus 7120 "File being analysed" rd873 "hello!" hi'))) 
> ['streptococcus', 
    '7120', 
    'File being analysed', 
    'rd873', 
    'hello!', 
    'hi'] 

看起來沒錯。

+0

你在OP的樣本字符串上測試了這個嗎?它不會做你想做的事。 (好了,現在它確實您編輯它之後。) – senshin

3

你想shlex.split,它給你你想要的報價行爲。

import shlex 

string = ' streptococcus 7120 "File being analysed" rd873 ' 
items = shlex.split(string) 

這不會破壞嵌入字符串多餘的空格,但你可以做到這一點與列表理解:

items = [" ".join(x.split()) for x in shlex.split(string)] 

看,媽媽,沒有正則表達式!

+0

非常感謝有沒有另一種方法除了使用shlex – user3284648

+0

嗯,有很多方法在做任何事情...... – kindall

+0

Shlex抓住單引號字符串爲好,我不確定這是否是有意的。 – U2EF1

相關問題