Skip to content

Instantly share code, notes, and snippets.

@sekimura
Created May 13, 2012 04:08
Show Gist options
  • Save sekimura/2678967 to your computer and use it in GitHub Desktop.
Save sekimura/2678967 to your computer and use it in GitHub Desktop.
Text (heredoc) strip margin in Python
import re
def strip_margin(text):
return re.sub('\n[ \t]*\|', '\n', text)
def strip_heredoc(text):
indent = len(min(re.findall('\n[ \t]*(?=\S)', text) or ['']))
pattern = r'\n[ \t]{%d}' % (indent - 1)
return re.sub(pattern, '\n', text)
print strip_margin(
"""I was reading a book "Programming Scala" and
|noticed that there is stripMargin method in
|RichString class in Scala.
|
|It's damn useful.""")
print strip_heredoc(
"""
And...
There is strip_heredoc in Ruby's String object.
Now you don't need a leader "|".
It does do a great job even if the string has
multi
level
indention.
It's damn useful too.
especially for usage docs like:
-h This message
yay or nay?""")
@benjcabalona1029
Copy link

Hey this is awesome, I was also coming from Scala looking for a strip margin, and found the strip_heredoc a bonus!

The multi-level indentation preserve is clever.

Originally from python, then switched to scala, then back to python looking for strip margin +2 :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment