10

How do split string by apostrophe ' and - ?

For example, given

string = "pete - he's a boy"
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Peter
  • 1,481
  • 4
  • 19
  • 37

6 Answers6

18

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

re.split("['-]", "pete - he's a boy")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Uwe Kleine-König
  • 3,426
  • 1
  • 24
  • 20
  • 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
  • 78,516
  • 15
  • 127
  • 132
2

This feels kind of hacky but you could do:

string.replace("-", "'").split("'")
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
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
  • 32,227
  • 27
  • 88
  • 117
0
>>> import re
>>> string = "pete - he's a boy"
>>> re.split('[\'\-]', string)
['pete ', ' he', 's a boy']

Hope this helps :)

fceruti
  • 2,405
  • 1
  • 19
  • 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
  • 26,771
  • 7
  • 38
  • 46