-3

I have a list of string and I want to remove one empty space between words:

classes_list = ['CLASS 8B CHEM  | MON | 10AM to 10:40AM', '--Rescheduled-- CLASS 8B MATHS  | MON | 11AM to 11:40AM', 'CLASS 8B HIST  | MON | 5PM to 5:40PM']
  • I want to remove one space after CHEM, MATHS, HIST
  • Look carefully there are two spaces after CHEM, MATHS, HIST

After which if I loop through the list it should print this:

'CLASS 8B CHEM | MON | 10AM to 10:40AM',
'--Rescheduled-- CLASS 8B MATHS | MON | 11AM to 11:40AM',
'CLASS 8B HIST | MON | 5PM to 5:40PM'

I don't know how to regular expression out-here if possible

Ayush Kumar
  • 123
  • 1
  • 11

2 Answers2

0

If your just trying to remove double spaces use replace

[i.replace(' ', ' ') for i in classes_list ]

['CLASS 8B CHEM | MON | 10AM to 10:40AM', '--Rescheduled-- CLASS 8B MATHS | MON | 11AM to 11:40AM', 'CLASS 8B HIST | MON | 5PM to 5:40PM']
Kenan
  • 10,163
  • 8
  • 32
  • 47
0

You could try the regex that matches zero or more white-space after CHEM, MATHS, HIST:

(?<=CHEM|HIST)\s*|(?<=MATHS)\s*

and use re.sub to replaces to a white space [ ].

See Regex-demo.

Python resource:

import re

classes_list = ['CLASS 8B CHEM  | MON | 10AM to 10:40AM',
                '--Rescheduled-- CLASS 8B MATHS  | MON | 11AM to 11:40AM',
                'CLASS 8B HIST  | MON | 5PM to 5:40PM']

#regex-pattern
rePattern=re.compile("(?<=CHEM|HIST)\s*|(?<=MATHS)\s*")

classes_list=[rePattern.sub(' ',x) for x in classes_list]
print(classes_list)

output:

['CLASS 8B CHEM | MON | 10AM to 10:40AM', '--Rescheduled-- CLASS 8B MATHS | MON | 11AM to 11:40AM', 'CLASS 8B HIST | MON | 5PM to 5:40PM']

Heo
  • 201
  • 1
  • 10
  • Why would you put MATHS in a separate expression? – tripleee Nov 23 '20 at 07:54
  • @tripleee In python, a look behind assertion has to be fixed width. Len of `MATHS` is 5, and the others are 4. They are not the same width that why I separated by `|` to work it. – Heo Nov 23 '20 at 08:14