16

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")
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Ricardo Rod
  • 8,453
  • 9
  • 27
  • 39

6 Answers6

21

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
Donald Miner
  • 38,889
  • 8
  • 95
  • 118
14
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.
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

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.

Gelineau
  • 2,031
  • 4
  • 20
  • 30
1

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

William Pourmajidi
  • 967
  • 11
  • 12
0

Use

var = input("Input the variable")
print("Your variable is " + var)

Note that var must be a string, if it isn't, convert it to a string with var = str(var).

For example

var = 5  # This is an integer, not a string
print("Var is " + str(var))

This solution is the easiest to read/understand, so better for beginners, as it is just simple string concatenation.

Tom Burrows
  • 2,225
  • 2
  • 29
  • 46
-4

You can also do this:

name = input("what is your name?")
print("this is",+name)
Lisa
  • 3,365
  • 3
  • 19
  • 30