My best here document

This is my paste, my wish: pray:

I want to create beautiful here documents in Python like Ruby's << ~!

From Ruby 2.4.0 Reference Manual »Literals» Here Documents (Line-Oriented String Literals)

By writing the start label with ~ like << ~ identifier, you can write the following here document. (Omitted) Remove whitespace from the beginning of every line, relative to the line with the least indentation. Note that lines that consist primarily of tabs and spaces are ignored to determine the depth of indentation. However, escaped tabs and spaces are treated the same as regular characters.

ruby


sayaka = 'Sayaka Miki'
kyoko = 'Sakura Kyoko'

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

puts(str)

stdout


<div>
  <ul>
    <li>Sayaka Miki</li>
    <li>Sakura Kyoko</li>
  </ul>
</div>

**here we go! Make it come true, incubator! !! ** **

The result of a wish for a here document surpassing entropy: innocent:

python


def heredoc(str):
  from textwrap import dedent

  return dedent(str).strip()


if __name__ == '__main__':
  sayaka = 'Sayaka Miki'
  kyoko = 'Sakura Kyoko'

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

  print(str)

stdout


<div>
  <ul>
    <li>Sayaka Miki</li>
    <li>Sakura Kyoko</li>
  </ul>
</div>

textwrap.dedent () and str.strip () 3 / library / stdtypes.html # str.strip) is also available!

My best reference article: sparkling_heart:

Recommended Posts

My best here document
Python here document
AWS Lambda Development My Best Practices
I tried my best to return to Lasso