LoginSignup
11
14

More than 5 years have passed since last update.

Pythonの文字列中に変数を埋め込みたい

Last updated at Posted at 2017-07-10

やりたかったこと

rubyの"some sentence...#{value}..."のようなこと。
検索すると変換指定子として%使うか、format関数を使う方法が出てきます。
けれども、前者の紹介例だと視線が前後するように感じたし、format関数はなにこれ長いという感想でした。

現状の結論

from functools import partial
myprint = partial(print, sep='')

hex_value = 0x1234
myprint('the value is %x'%hex_value,' and...')

変数1つごとに、,で文字列を区切ると近いことができる。
上記の例では,でのスペース挿入を防いでいるが、問題なければそのままprint関数でいいと思います。
出力フォーマットの指定も一緒にできているのでいいんじゃないかと思ってます。
もっといい機能があったらどなたか教えてください。

(追記)
3.6以上で使えるformatted string literalがまさに求めていた記法でした。
@naari さんありがとうございます。(コメント参照)

11
14
3

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
11
14