3

Possible Duplicate:
Python Regular expression must strip whitespace except between quotes

I need to remove all whitespaces in a file that are not inside single or double quotes (i.e. not in a string).

I've found this solution Python Regular expression must strip whitespace except between quotes

but that works only for double quotes

Community
  • 1
  • 1
osiris81
  • 487
  • 4
  • 15

1 Answers1

4

Remove whitespace outside quotes:

import re

parts = re.split(r"""("[^"]*"|'[^']*')""", text)
parts[::2] = map(lambda s: "".join(s.split()), parts[::2]) # outside quotes
print("".join(parts))
jfs
  • 399,953
  • 195
  • 994
  • 1,670