10

How do split string by apostrophe ' and - ?

For example, given

string = "pete - he's a boy"
wjandrea
  • 23,210
  • 7
  • 49
  • 68
Peter
  • 1,443
  • 4
  • 18
  • 36

6 Answers6

18

You can use the regular expression module's split function:

re.split("['-]", "pete - he's a boy")
wjandrea
  • 23,210
  • 7
  • 49
  • 68
Uwe Kleine-König
  • 3,304
  • 1
  • 22
  • 19
  • 1
    that doesn´t work you need to escape the characters like one answer below =P – fceruti May 05 '11 at 08:03
  • @fceruti You only need to escape the single-quote if you're using a single-quoted string, but this string is double-quoted. The hyphen doesn't need to be escaped at all. – wjandrea May 18 '22 at 19:17
9
string = "pete - he's a boy"
result = string.replace("'", "-").split("-")
print result

['pete ', ' he', 's a boy']
Cédric Julien
  • 74,806
  • 15
  • 120
  • 127
2

This feels kind of hacky but you could do:

string.replace("-", "'").split("'")
zeekay
  • 49,858
  • 13
  • 107
  • 105
2

This can be done without regular expressions. Use the split method on string ( and using list comprehensions - effectively the same as @Cédric Julien's earlier answer

First split once on one splitter e.g. '-' then split each element of the array

l = [x.split("'") for x in "pete - he's a boy".split('-')]

Then flattern the lists

print ( [item for m in l for item in m ] )

giving

['pete ', ' he', 's a boy']
mmmmmm
  • 31,464
  • 27
  • 87
  • 113
0
>>> import re
>>> string = "pete - he's a boy"
>>> re.split('[\'\-]', string)
['pete ', ' he', 's a boy']

Hope this helps :)

fceruti
  • 2,373
  • 1
  • 18
  • 28
0
import re
string = "pete - he's a boy"
print re.findall("[^'-]+",string)

result

['pete ', ' he', 's a boy']

.

and if you want no blank before nor after each item after spliting:

import re
string = "pete - he's a boy"
print re.findall("[^'-]+",string)
print re.findall("(?! )[^'-]+(?<! )",string)

result

['pete', 'he', 's a boy']
eyquem
  • 25,715
  • 6
  • 36
  • 44