Insert variable values into a string

Viewed 42491

I want to introduce a variable [i] into a string in Python.

For example look at the following script. I just want to be able to give a name to the image, for example geo[0].tif ... to geo[i].tif, or if you use an accountant as I can replace a portion of the value chain to generate a counter.

data = self.cmd("r.out.gdal in=rdata out=geo.tif")
self.dataOutTIF.setValue("geo.tif")
6 Answers

If you are using python 3, then you can use F-string. Here is an example

 record_variable = 'records'    
 print(f"The element '{record_variable}' is found in the received data")

in this case, the output will be like:

he element 'records' is found in the received data

If you are using python 3.6+, the best solution is using f-strings:

data = self.cmd(f"r.out.gdal in=rdata out=geo{i}.tif")
self.dataOutTIF.setValue(f"geo{i}.tif")

It is the more readable and performant solution.

Related