DEV Community

QUANON
QUANON

Posted on

My best Python heredoc like Ruby's one

Ruby (I want to do like this with Python)

sayaka = '美樹 さやか'
kyoko = '佐倉 杏子'

str = <<~HEREDOC
  <div>
    <ul>
      <li>#{sayaka}</li>
      <li>#{kyoko}</li>
    </ul>
  </div>
HEREDOC

puts(str)
Enter fullscreen mode Exit fullscreen mode
<div>
  <ul>
    <li>美樹 さやか</li>
    <li>佐倉 杏子</li>
  </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Like above, I want to do:

  • Ignore leading whitespaces at each line
  • Ignore break line after the first '''

Python (How to do that)

def heredoc(str):
  from textwrap import dedent

  return dedent(str).strip()


if __name__ == '__main__':
  sayaka = '美樹 さやか'
  kyoko = '佐倉 杏子'

  str = heredoc(f'''
    <div>
      <ul>
        <li>{sayaka}</li>
        <li>{kyoko}</li>
      </ul>
    </div>
  ''')

  print(str)
Enter fullscreen mode Exit fullscreen mode
<div>
  <ul>
    <li>美樹 さやか</li>
    <li>佐倉 杏子</li>
  </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)