LoginSignup
2
3

More than 3 years have passed since last update.

【python3】変数名をキーとして文字列のformatを行う

Last updated at Posted at 2019-11-01

実装した関数

from inspect import currentframe,getargvalues

def varfmt(target,*argv):  
    return target.format(**getargvalues(currentframe().f_back).locals)  

【※追記※】@shiracamus さんより、python3.6以降なら以下の書き方でOKとのコメントを頂きました。
ありがとうございます!

def hoge_aa_print(hoge, aaa):
    print(f"{hoge} {aaa}")

hoge_aa_print(10, 20)

[参考]
https://qiita.com/AnchorBlues/items/f7725ba87ce349cb0382
https://docs.python.org/ja/3/library/inspect.html

example

from inspect import currentframe,getargvalues

def varfmt(target,*argv):  
    return target.format(**getargvalues(currentframe().f_back).locals)  


def hoge_aa_print(hoge,aaa):
    print(varfmt("{hoge} {aaa}",hoge,aaa))

hoge_aa_print(10,20)

このように、変数名をキーとして文字列のformatを行うことが出来ます。

補足

誤り、マサカリ、苦情、鬱憤晴らし等有りましたらコメントお願いします。

2
3
4

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