Please delete me Please delete me - 7 months ago 36
Python Question

Python Condense CSS margin and padding

How can I condense CSS margin and padding with Python ?

margin: 10px 10px 10px 10px;, 10px 10px 10px; and 10px 10px; down to margin: 10px;
margin: 10px 20px 10px 20px; down to margin: 10px 20px;
padding: 10px 20px 10px 20px; down to padding: 10px 20px;

Answer

This could be done with a regular expression:

result = re.sub(r"(margin|padding): ([^;]+?)(?:\s+\2)+;", r"\1: \2;", subject)

will replace any repeating text between margin: or padding: and the next semicolon with the first repetition.

So, for example:

>>> import re
>>> subject = """margin: 10px 10px 10px 10px;
... margin: 10px 20px 10px 20px;
... padding: 10px 20px 10px 20px;
... padding: 10px 10px 10px;"""
>>> result = re.sub(r"(margin|padding): ([^;]+?)(?:\s+\2)+;", r"\1: \2;", subject)
>>> print(result)
margin: 10px;
margin: 10px 20px;
padding: 10px 20px;
padding: 10px;
Comments