bachurim09
bachurim09

Reputation: 1811

Splitting by character using regular expressions

I want to split a string by the char '-' along with the spaces to the left and right of it. How can I do this?

I tried a few things:

a.split('[\s]-[\s]')
a.split( *- *)
a.split(\s-\s)

Upvotes: 1

Views: 99

Answers (3)

the wolf
the wolf

Reputation: 35532

s='one - two - three - four'

print re.split(r'\s*-\s*',s)

prints:

['one', 'two', 'three', 'four']

Upvotes: 0

Kendall Frey
Kendall Frey

Reputation: 44326

If you want to remove all spaces around the '-', use this regex.

\s*-\s*

If you only want one optional space on either side, use this one.

\s?-\s?

Upvotes: 2

ludaavics
ludaavics

Reputation: 678

import re
s = 'abc-abc- abc -abc - abc'
r = re.compile('\s*-\s*')
r.split(s)

Will give

['abc', 'abc', 'abc', 'abc', 'abc']

Upvotes: 2

Related Questions