Python: divide the string by 'and -

How to split a line by an apostrophe 'and -?

For example, given string = "pete - he a boy"

+5
source share
6 answers

You can use the decomposition function of the regular expression module:

re.split("['-]", "pete - he a boy")
+15
source
string = "pete - he a boy"
result = string.replace("'", "-").split("-")
print result

['pete ', ' he',  a boy']
+6
source

, :

string.replace("-", "'").split("'")
+2

. split ( ) - , @Cédric Julien fooobar.com/questions/1073506/...)

,

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

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

['pete ', ' he',  a boy']
+2
>>> import re
>>> string = "pete - he a boy"
>>> re.split('[\'\-]', string)
['pete ', ' he',  a boy']

, :)

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

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

.

, :

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

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

All Articles