2017-04-04 46 views
-2
string="i-want-all-dashes-split" 

print(split(string,"-")) 

所以我想輸出是:你如何分割所有某個字符的Python中

string=(I,-,want,-,all,-,dashes,-,split) 

我基本上要分區中的所有「 - 」的。

+0

'進口重; print(','。join(re.split('( - )',string)))' – zondo

回答

3
>>> import re 
>>> string = "i-want-all-dashes-split" 

>>> string.split('-')     # without the dashes 
['i', 'want', 'all', 'dashes', 'split'] 

>>> re.split('(-)', string)   # with the dashes 
['i', '-', 'want', '-', 'all', '-', 'dashes', '-', 'split'] 

>>> ','.join(re.split('(-)', string)) # as a string joined by commas 
'i,-,want,-,all,-,dashes,-,split' 
0

你可以使用這個功能太:

代碼:

def split_keep(s, delim): 

    s = s.split(delim) 
    result = [] 

    for i, n in enumerate(s): 
     result.append(n) 
     if i == len(s)-1: pass 
     else: result.append(delim) 

    return result 

用法:

split_keep("i-want-all-dashes-split", "-") 

輸出:

['i', '-', 'want', '-', 'all', '-', 'dashes', '-', 'split'] 
+0

這不太合適。在8中,你把d和我敢肯定你的意思是把delim,但編輯後,把它放入我的代碼,輸出是['我','想',' - ','全',' - ','破折號',' - ','分割',' - ']。它將第一個短劃線移動到字符串的最後部分, –

+0

糟糕!只是修復它..謝謝! –

0
string="i-want-all-dashes-split" 

print 'string='+str(string.split('-')).replace('[','(').replace(']',')').replace(' ','-,') 

>>>string=('i',-,'want',-,'all',-,'dashes',-,'split') 
0

使用從str類分割功能:

text = "i-want-all-dashes-split" 
splitted = text.split('-') 

值分裂像一個波紋管的列表:

['i', 'want', 'all', 'dashes', 'split'] 

如果你想作爲元組輸出,像下面的代碼那樣做:

t = tuple(splitted) 
('i', 'want', 'all', 'dashes', 'split') 
0
string="i-want-all-dashes-split" 
print(string.slip('-')) 
# Output: 
['i', 'want', 'all', 'dashes', 'split'] 

string.split()
裏面的(),你可以把你的分隔符( ' - '),如果你不把任何東西這將是( '')默認情況下。 你可以做一個函數:

def spliter(string, delimiter=','): # delimiter have a default argument (',') 
    string = string.split(delimiter) 
    result = [] 
    for x, y in enumerate(string): 
     result.append(y) 
     if x != len(string)-1: result.append(delimiter) 
    return result 

輸出:

['i', '-', 'want', '-', 'all', '-', 'dashes', '-', 'split']