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")
To declare variables in JavaScript, you need to use the var, let, or const keyword. Whether it is a string or a number, use the var, let, or const keyword for its declaration. But for declaring a string variable we had to put the string inside double quotes or single quotes.
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.
If you can depend on having Python >= version 3.6, then you have another attractive option, which is to use the new formatted string literal (f-string) syntax to insert variable values. An f at the beginning of the string tells Python to allow any currently valid variable names as variable names within the string.
You can use the operator %
to inject strings into strings:
"first string is: %s, second one is: %s" % (str1, "geo.tif")
This will give:
"first string is: STR1CONTENTS, second one is geo.tif"
You could also do integers with %d
:
"geo%d.tif" % 3 # geo3.tif
data = self.cmd("r.out.gdal in=rdata out=geo{0}.tif".format(i))
self.dataOutTIF.setValue("geo{0}.tif".format(i))
str.format(*args, **kwargs)
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
>>> "The sum of 1 + 2 is {0}".format(1+2) 'The sum of 1 + 2 is 3'
See Format String Syntax for a description of the various formatting options that can be specified in format strings.
This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.
New in version 2.6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With