string.Template
次のコードを実行したときの出力として、正しいものを1つ選べ。
from string import Template
t = Template("${village}folk send $$10 to $cause.")
print(t.substitute(village="Nottingham", cause="the ditch fund"))
- A
${village}folk send $$10 to $cause. - B
Nottinghamfolk send $$10 to the ditch fund. - C
KeyErrorが発生する。 - 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. |
- A
誤り。substitute で置き換えられる。
- B
誤り。
$$は1つの$になる。 - C
誤り。必要な値はすべて渡している。
- D
正しい。
$名前や${名前}が値に置き換えられ、$$は$という文字になる。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。