1

I have some strings such as abc pre - school unit or abc pre / school district that I would need to delete additional spaces before and after hyphen and slash. These examples will become abc pre-school unit and abc pre/school district.

I attempted this solution, but this works just replacing either slash or hyphen with hyphen. How can I delete the spaces to get these strings?

abc pre-school unit abc pre/school district

import re

text= ['abc pre - school unit', 'abc pre / school district']

for name in text:
    tmp= re.sub("\s+[-/]\s+" , "-", name)

    print(tmp)
John Barton
  • 1,581
  • 4
  • 25
  • 51

3 Answers3

2

You could capture the symbol and then replace with that:

text = ['abc pre - school unit', 'abc pre / school district']

for name in text:
    tmp = re.sub("\s+([/-])\s+" , "\\1", name)
    print(tmp)

This prints:

abc pre-school unit
abc pre/school district
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

In your case you need assign it back as well

text= ['abc pre - school unit', 'abc pre / school district']
tmp=[]
for name in text:
    tmp.append(re.sub("\s+([-/])\s+" , r'\1', name))

tmp
['abc pre-school unit', 'abc pre/school district']

Or

newlist=list(map(lambda x : re.sub("\s+([-/])\s+" , r'\1', x),text))
BENY
  • 317,841
  • 20
  • 164
  • 234
1

in re.sub, you can capture a pattern by putting it in braces. You can refer to it in the replacement by using positional arguments such as \1, \2, \3

So the solution would be: for name in text: tmp.append(re.sub("\s+([-/])\s+" , "\1", name))

Catch22
  • 391
  • 2
  • 5