在字符串中插入变量值

2024-05-29 05:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python中的字符串中引入一个变量[i]

例如,看下面的脚本。我只想给图像起个名字,例如geo[0].tif。。。到geo[i].tif,或者如果您使用会计,我可以替换价值链的一部分来生成计数器

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

Tags: 字符串in图像self脚本cmddata计数器
3条回答

如果您使用的是Python3,那么就可以使用F-string。这里有一个例子

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

在这种情况下,输出如下:

在接收到的数据中找到元素“记录”

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.

可以使用运算符%将字符串注入字符串:

"first string is: %s, second one is: %s" % (str1, "geo.tif")

这将提供:

"first string is: STR1CONTENTS, second one is geo.tif"

您还可以使用%d进行整数运算:

"geo%d.tif" % 3   # geo3.tif

相关问题 更多 >

    热门问题