在python中将变量值插入字符串

2024-05-15 02:03:35 发布

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

As在python中将变量[i]引入字符串。

例如,看看下面的脚本,我只想给图像命名,例如geo[0]。蒂芙。。。给geo[i]。tiff,或者如果你使用会计,因为我可以替换价值链的一部分来生成计数器。

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

    self.dataOutTIF.setValue("geo.tif")

谢谢你的回答


Tags: 字符串图像self脚本cmddataas计数器
3条回答
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

使用

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

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

例如

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

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

相关问题 更多 >

    热门问题