Python 模擬試験

Python基礎 模擬試験 第3回 問38・11章 標準ライブラリめぐり Part II(テンプレート)

string.Template

次のコードを実行したときの出力として、正しいものを1つ選べ。

from string import Template
t = Template("${village}folk send $$10 to $cause.")
print(t.substitute(village="Nottingham", cause="the ditch fund"))
  1. A

    ${village}folk send $$10 to $cause.

  2. B

    Nottinghamfolk send $$10 to the ditch fund.

  3. C

    KeyError が発生する。

  4. D

    Nottinghamfolk send $10 to the ditch fund.

正解と解説を見る

正解:D

string.Template では、$名前 を値に置き換え、$$ で $ という文字を表す。

順実行する行実行後の変数
1`from string import Template`—
2`t = Template("${village}folk send $$10 to $ca…`—
3`print(t.substitute(village="Nottingham", caus…`—
結果実際の出力Nottinghamfolk send $10 to the ditch fund.

学習のポイント:値が足りないときに、substitute は KeyError、safe_substitute はそのまま残すことを押さえる。

この問題を演習で解く →

問題一覧へ

このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。