Skip to content

Instantly share code, notes, and snippets.

@23maverick23
Last active January 1, 2023 14:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 23maverick23/5789601 to your computer and use it in GitHub Desktop.
Save 23maverick23/5789601 to your computer and use it in GitHub Desktop.
Python: Strip spaces between tags
#!/usr/bin/env python
print re.sub('\s+(?=<)', '', xml_string)
# This regex will turn a prettyprinted XML string into a spaceless
# string which is sometimes easier to deal with.
# Example response from xml.etree.ElementTree.fromstring(xml)
# <response>
# <Auth status="0"/>
# <Read status="0">
# <Invoice>
# <id>4</id>
# <number>983</number>
# <customerid>204</customerid>
# <total>12.00</total>
# </Invoice>
# </Read>
# </response>
# When the above is printed in the terminal it will look like this
xml_string = '''
<response>\n <Auth status="0"/>\n <Read status="0">\n <Invoice>\n <id>1</id>\n <number>234</number>\n
<customerid>204</customerid>\n <total>99.00</total>\n </Invoice>\n </Read>\n</response>\n
'''
# Passing that xml_string through the regex expression will print like this
'''<response><Auth status="0"/><Read status="0"><Invoice><id>1</id><number>234</number><customerid>204</customerid><total
>99.00</total></Invoice></Read></response>'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment