LoginSignup
2
3

More than 1 year has passed since last update.

pythonのformatで分割して代入/別々に代入/段階的に代入

Last updated at Posted at 2021-07-17

やりたいこと

pythonの文字列処理でformatというのがあります。
例えば、

test1.py
format_str = "My name is {name}. I am from {place}. Nice to meet you."

what_to_say = format_str.format(name="Bob", place="Beppu")
print(what_to_say)
実行結果
My name is Bob. I am from Beppu. Nice to meet you.

となります。

ただ、以下のようにするとエラーが出ます。

test2.py
format_str = "My name is {name}. I am from {place}. Nice to meet you."
what_to_say = format_str.format(name="Alice")
what_to_say = what_to_say.format(place="Tsugaru")
print(what_to_say)
実行結果
Traceback (most recent call last):
  File "●●.py", line ●, in <module>
    what_to_say = format_str.format(name="Alice")
KeyError: 'place'

formatでplaceが指定されていない!と怒られてしまいました。
どうやらstr.format()を使うときは、formatで定義されている変数をすべて一気に入れないとエラーになるようです。

ではこのエラーを回避して、formatの文章に分割して代入/別々に代入/段階的に代入したいときにどうすればいいか、という話になると思います。
そもそも、一気に代入するのが普通なので、こういうケースはほとんどないのですが、以前記事にした、
Twitter Botで長い文章をツイート可能ギリギリの長さに調節する
といったケースでは、書き出し以外の文章を代入して、その後書き出しを代入する、という手順をとる場合は、段階的に代入がしたいです。
(もちろん他の手順をとればいいだけの話ですが、今回はこの方法ですすめるとします)

解決策

もっと他にいい方法はあるんじゃないかともいましたが、以下の方法でいけました。

test3.py
format_str = "My name is {name}. I am from {place}. Nice to meet you."
what_to_say = format_str.format(name="Alice", place="{place}")
what_to_say = what_to_say.format(place="Tsugaru")
print(what_to_say)
実行結果
My name is Alice. I am from Tsugaru. Nice to meet you.
2
3
1

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
2
3