How do split string by apostrophe '
and -
?
For example, given
string = "pete - he's a boy"
How do split string by apostrophe '
and -
?
For example, given
string = "pete - he's a boy"
You can use the regular expression module's split function:
re.split("['-]", "pete - he's a boy")
string = "pete - he's a boy"
result = string.replace("'", "-").split("-")
print result
['pete ', ' he', 's a boy']
This feels kind of hacky but you could do:
string.replace("-", "'").split("'")
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']
>>> import re
>>> string = "pete - he's a boy"
>>> re.split('[\'\-]', string)
['pete ', ' he', 's a boy']
Hope this helps :)
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']