string="i-want-all-dashes-split"
print(split(string,"-"))
所以我希望输出为:
string=(I,-,want,-,all,-,dashes,-,split)
我基本上想要对所有“ - ”进行分区。
答案 0 :(得分: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'
答案 1 :(得分: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']
答案 2 :(得分:0)
string="i-want-all-dashes-split"
print 'string='+str(string.split('-')).replace('[','(').replace(']',')').replace(' ','-,')
>>>string=('i',-,'want',-,'all',-,'dashes',-,'split')
答案 3 :(得分:0)
使用str class中的split函数:
text = "i-want-all-dashes-split"
splitted = text.split('-')
拆分的值是一个类似下面的列表:
['i', 'want', 'all', 'dashes', 'split']
如果您希望将输出作为元组,请按照以下代码执行:
t = tuple(splitted)
('i', 'want', 'all', 'dashes', 'split')
答案 4 :(得分:0)
string="i-want-all-dashes-split"
print(string.slip('-'))
# Output:
['i', 'want', 'all', 'dashes', 'split']
string.split()
在()中,你可以把你的分隔符(&#39; - &#39;),如果你没有把它放到任何东西(&#39;,&#39;),默认情况下。
你可以做一个功能:
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']