3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

for文で変数名を回す方法

Last updated at Posted at 2022-11-09

for文で変数名を回す方法

execを使って回す方法

execを使えばシンプルに書けることに気が付いたのでメモしておく。
ファイル名を付けるときにも役立ちそう。

in
for i in range(5):
    exec('print("file_" + str(i))')
out
file_0
file_1
file_2
file_3
file_4
file_5

追記

コメント欄より、ほかの方法を掲載します。

formatを使った方法

for i in range(5):
    print(f"file_{i}")
for i in range(5):
    print("file" + str(i))

execを使う方法

file_0,file_1,file_2,file_3,file_4 = 0,1,2,3,4
for i in range(5):
    exec("print(file_{i})")
3
3
6

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?