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! !! ** **
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!
textwrap.dedent ()
.