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

print(split(string,"-"))

So I want the output to be:

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

I basically want to partition all the "-"'s.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Darth Vador
  • 169
  • 2
  • 4
  • 12

5 Answers5

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'
Uriel
  • 15,579
  • 6
  • 25
  • 46
0

You can use this function too:

Code:

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

Usage:

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

Output:

['i', '-', 'want', '-', 'all', '-', 'dashes', '-', 'split']
dot.Py
  • 5,007
  • 5
  • 31
  • 52
  • That's not quite working. In like 8 you put d and I'm pretty sure you meant to put delim, But after editing that and putting that into my code, the output is ['i', 'want', '-', 'all', '-', 'dashes', '-', 'split', '-']. It's moving the first dash to the last part of string, – Darth Vador Apr 04 '17 at 17:22
  • Oops! Just fixed it.. Thanks! – dot.Py Apr 04 '17 at 17:24
0
string="i-want-all-dashes-split"

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

>>>string=('i',-,'want',-,'all',-,'dashes',-,'split')
litepresence
  • 3,109
  • 1
  • 27
  • 35
0

Use the split function from str class:

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

The value of splitted be a list like the one bellow:

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

If you want the output as a tuple, do it like in the code bellow:

t = tuple(splitted)
('i', 'want', 'all', 'dashes', 'split')
daniboy000
  • 1,069
  • 2
  • 16
  • 26
0
string="i-want-all-dashes-split"
print(string.slip('-'))
# Output:
['i', 'want', 'all', 'dashes', 'split']

string.split()
Inside the () you can put your delimiter ('-'), if you don't put anything it would be (',') by default. You can make a function:

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

Output:

['i', '-', 'want', '-', 'all', '-', 'dashes', '-', 'split']
Ender Look
  • 2,303
  • 2
  • 17
  • 41