LoginSignup
14
8

More than 5 years have passed since last update.

素人の言語処理100本ノック:07

Last updated at Posted at 2016-09-18

言語処理100本ノック 2015の挑戦記録です。環境はUbuntu 16.04 LTS + Python 3.5.2 :: Anaconda 4.1.1 (64-bit)です。過去のノックの一覧はこちらからどうぞ。

第1章: 準備運動

07.テンプレートによる文生成

引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.

出来上がったコード:

main.py
# coding: utf-8


def format_string(x, y, z):
    '''引数x, y, zを受け取り「x時のyはz」という文字列を返す

    引数:
    x, y, z -- 埋め込むパラメータ
    戻り値:
    整形した文字列
    '''
    return '{hour}時の{target}は{value}'.format(hour=x, target=y, value=z)


# テスト
x = 12
y = '気温'
z = 22.4
print(format_string(x, y, z))

実行結果:

端末
12時の気温は22.4

str.format()の指定方法は書式指定文字列の文法に解説があります。使っていかないと、なかなか覚えられないですね。


あと、string.Templateクラスというのもありますね。こちらの方が出題の意図に近いかもしれないので、こちらでも書いてみます。

出来上がったコード:

main2.py
# coding: utf-8
from string import Template


def format_string(x, y, z):
    '''引数x, y, zを受け取り「x時のyはz」という文字列を返す

    引数:
    x, y, z -- 埋め込むパラメータ
    戻り値:
    整形した文字列
    '''
    s = Template('$hour時の$targetは$value')
    return s.substitute(hour=x, target=y, value=z)


# テスト
x = 12
y = '気温'
z = 22.4
print(format_string(x, y, z))

実行結果:

端末
12時の気温は22.4

 
8本目のノックは以上です。誤りなどありましたら、ご指摘いただけますと幸いです。

14
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
8