< Back

Pythonのヒアドキュメント

Python ヒアドキュメント

Qiitaでtitle:python title:ヒアドキュメントで調べると1件だけで、あまりまとめられてなかったので記事書きます!
初めてPython使う人と、たまにPython使うひとがあれ書き方忘れたなって時みるようなレベル感で、つらつらとまとめられたらと思います。ツッコミとかあればコメント欄でお願いします。

version.py
python -V
Python 2.7.13

最終目標物

matome.py
import textwrap
string = textwrap.dedent('''
  This is a {what}.
  I'm from {where}.
''').format(what="apple", where="Chiba").strip()
print(string)

"""
This is a apple.
I'm from Chiba.
"""

内容

  • ヒアドキュメントの使い方
  • インデックス削除
  • 変数展開

ヒアドキュメントとは

こういう
改行
が入った文章を扱いやすくするもの。
sample.py
# \nが改行の意味

# こうやって\nを大量に書かなくても"×3で囲むと扱いやすくなる。
string = "こういう\n改行\nが入った文章を扱いやすくするもの。"

# こう書くのがヒアドキュメント(風)
string = """
こういう
改行
が入った文章を扱いやすくするもの。
"""

ヒアドキュメントと複数行コメント

sample.py
# coding: utf-8

# 一行コメントは#を使って

"""
複数行コメントは"×3です。
"""

'''
こちらも複数行コメント
です!!
'''

こんな感じでコメントアウトされてない部分は変な色になるので見分けてください
ここエラー起こします

日本語扱うときは最初に# coding: utf-8

普通のヒアドキュメント

sample.py

# これが普通のヒアドキュメント

string = '''This is a pen.
I'm from Tokyo.'''

print(string)

# 出力結果
"""
This is a pen.
I'm from Tokyo.
"""

上下比べてください。
次のように書く方が見通しがいいのですが前後に改行が足されるので、その修正をしていきます。

sample.py

string = '''
This is a pen.
I'm from Tokyo.
'''

print(string)

# 出力結果

"""

This is a pen.
I'm from Tokyo.

"""

# 上下に余白あいちゃった。

上下の余白の消し方

  • [1:-1]
  • strip()
  • バックスラッシュ\

Python のヒアドキュメントを見やすくする小技
こちらの記事とコメント欄を参考にさせていただきました。

上下の余白の消し方 [1:-1]

sample.py

string = '''
This is a pen.
I'm from Tokyo.
'''[1:-1]

print(string)

# 出力結果
"""
This is a pen.
I'm from Tokyo.
"""

[1:-1]の使い方をみてみる。

sample.py

print("test123456789"[1:-1])

# 出力結果
"""
est12345678
"""

上下の余白の消し方 strip()

sample.py

string = '''
This is a pen.
I'm from Tokyo.
'''.strip()

print(string)

# 出力
This is a pen.
I'm from Tokyo.

strip()は前後の空白文字を削除してくれます。
参考記事[python]strip()の引数を省略すると空白だけでなく改行も除去される

sample.py

print("     space5     ".strip())
print("     \nspace5\n     ".strip())

# どちらも改行記号とスペースが削除されます。
"""
space5
"""

上下の余白の消し方 バックスラッシュ\

sample.py

string = '''\
This is a pen.
I'm from Tokyo.\
'''

print(string)

# 出力

"""
This is a pen.
I'm from Tokyo.
"""

バックスラッシュ\は、Pythonのコードの途中で改行したいときとか、長くなって読みやすさを重視したいときとかに使います。見た目は改行してるけど、pythonとしては改行を無視して読み込みをするやつです。

print ("te\
st")
print \
  ("test")

"""
test
test
"""

インデント削除

インデントがさがってるときのヒアドキュメントのインデント削除をみていきます。

if True:
    string = '''
        This is a pen.
        I'm from Tokyo.
        '''.strip()
    print(string)

"""
        This is a pen.
        I'm from Tokyo.     
"""

import textwrap
このtextwrapというものをimportする。これが一番ラクです。

sample.py

import textwrap

if True:
    string = '''
        This is a pen.
        I'm from Tokyo.
        '''
    print(string)

print (textwrap.dedent(string).strip())

"""
--------
This is a pen.
I'm from Tokyo.
--------
"""

textwrap.dedent(string)が各行のインデントを削除してくれます。

変数展開

すごく参考になるリンクはこちら。
Pythonで文字列中の変数展開をするときの書式について調べたのでメモ

sample.py
string = '''
This is a {what}.
I'm from {where}.
'''.format(what="apple", where="Chiba").strip()

print(string)

"""
--------
This is a apple.
I'm from Chiba.
--------
"""

{what}
what="apple"
{}つけたり、whatと""で囲まなかったりと、使うたびに調べそうな気がしてます。

まとめ

matome.py
import textwrap
string = textwrap.dedent('''
  This is a {what}.
  I'm from {where}.
''').format(what="apple", where="Chiba").strip()
print(string)

"""
This is a apple.
I'm from Chiba.
"""

なんとなくヒアドキュメントで使いそうなものをつらつらと書いてきましたが、足りない部分とかもたくさんあると思いますが、参考になれば!