Problem in saving specific file name in python 3

227 Views Asked by At

After running the following program in jupyter lab the saved filename is ('test_C0_s50_d', 1, 't', 2, '18_l1w'), but I don't want parenthesis, comma, and spaces in the file name. I want something similar to test_C0_s50_d1t2_18_l1w in the filename so that when changing i and j value I can find another name.

i = 1
j = 2
plt.scatter(1,2)
saving  = 'test_C0_s50_d',i,'t',j,'18_l1w'
print(saving)
plt.savefig("{0}.png".format(saving))
plt.show()
3

There are 3 best solutions below

0
On

You need to use format (or similar) to get the numbers where you want them:

saving  = 'test_C0_s50_d{0}t{1}18_l1w'.format(i, j)
0
On

One way of doing this is to create a list of strings you want to use then call join function:

i = 1
j = 2
prefix = "test_C0_s50_d"
names = [prefix, str(i), str(j)]
saving = "_".join(names)
0
On

Use fast string (f string) which is easy also!

i = 1
j = 2
filename  = f'test_C0_s50_d{i}t{j}18_l1w'
plt.savefig(filename)
plt.show()