Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字符串中插入变量值_Python - Fatal编程技术网

Python 在字符串中插入变量值

Python 在字符串中插入变量值,python,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") 您可以使用运算符%将字符串插入字符串: "first string is: %s

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

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

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

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

"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
执行字符串格式化操作。在其上执行此操作的字符串 方法可以包含文本 分隔的文本或替换字段 用大括号{}。每个替换字段 包含 位置参数,或 关键字参数。返回一份 每次替换的字符串 字段将替换为字符串 相应参数的值

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
有关各种格式的说明,请参见格式字符串语法 可在中指定的选项 格式化字符串

这种字符串格式化方法是Python 3.0中的新标准,并且 应优先于% 以字符串形式描述的格式设置 在新代码中格式化操作

New in version 2.6.
您也可以这样做:

name = input("what is your name?")
print("this is",+name)
使用


请注意,
var
必须是字符串,如果不是,请使用
var=str(var)
将其转换为字符串

比如说

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

此解决方案最容易阅读/理解,因此对初学者来说更好,因为它只是简单的字符串连接。

如果您使用的是python 3.6+,最好的解决方案是使用f字符串:

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

这是一个更具可读性和性能的解决方案。

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

 record_variable = 'records'    
 print(f"The element '{record_variable}' is found in the received data")
在这种情况下,输出如下:


在收到的数据中可以找到元素“records”

这些天是
。format
被认为比我的解决方案更像Python?是的,它是官方认可的,而你的解决方案不是,iirc。无需责备:)@orangeoctopus,只为Python2.6+谢谢!我会开始用这个。实际上,这个不起作用。。你是说打印(“这是”+名字)?
var = 5  # This is an integer, not a string
print("Var is " + str(var))
data = self.cmd(f"r.out.gdal in=rdata out=geo{i}.tif")
self.dataOutTIF.setValue(f"geo{i}.tif")
 record_variable = 'records'    
 print(f"The element '{record_variable}' is found in the received data")