このステップでは、Python の空白文字について学びます。空白文字は、空のスペースを表す文字です。これらは、コードの解釈と表示に影響を与えるため、プログラミングにおいて重要です。空白を理解することは、クリーンで読みやすい Python コードを書くために不可欠です。
-
LabEx 環境で VS Code エディタを開きます。
-
~/project ディレクトリに whitespace_demo.py という名前の新しいファイルを作成します。
touch ~/project/whitespace_demo.py
-
エディタで whitespace_demo.py ファイルを開き、以下の内容を追加します。
## Demonstrating whitespace characters
space_char = " "
tab_char = "\t"
newline_char = "\n"
carriage_return_char = "\r"
vertical_tab_char = "\v"
form_feed_char = "\f"
print("This", space_char, "is", space_char, "separated", space_char, "by", space_char, "spaces.")
print("This\tis\tseparated\tby\ttabs.")
print("This" + newline_char + "is" + newline_char + "on" + newline_char + "multiple" + newline_char + "lines.")
print("This" + carriage_return_char + "will overwrite the beginning of the line.")
print("Vertical" + vertical_tab_char + "Tab")
print("Form" + form_feed_char + "Feed")
このスクリプトは、各空白文字に対する変数を定義し、それらを print() 文で使用してそれらの効果を示します。
-
python コマンドを使用してスクリプトを実行します。
python ~/project/whitespace_demo.py
以下のような出力が表示されるはずです。
This is separated by spaces.
This is separated by tabs.
This
is
on
multiple
lines.
will overwrite the beginning of the line.
Vertical Tab
Form Feed
各空白文字が出力の書式設定にどのように影響するかに注目してください。改行文字は改行を作成し、タブ文字は水平方向の間隔を作成します。復帰文字は行の先頭を上書きします。垂直タブと改ページ文字は、使用しているターミナルによっては表示されない場合があります。