2010-07-29 76 views
10

由於在python中將變量[i]引入到字符串中。將變量值插入python中的字符串

例如看下面的腳本,我只想給一個圖像命名,例如geo [0]。 Tiff ...到地理[i]。 tiff,或者如果您使用會計師,我可以替換價值鏈的一部分來生成計數器。

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

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

感謝您的回答

回答

10
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) 

執行字符串格式化操作。調用此方法的字符串可以包含文字 文本或由大括號{}分隔的替換字段 。每個替換字段 包含 位置參數的數字索引或 關鍵字參數的名稱。返回 字符串的副本,其中每個替換字段 被字符串 替換爲相應參數的值。

>>> "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. 
+0

這些天''格式'認爲比我的解決方案pythonic? – 2010-07-29 22:08:13

+0

是的,它是官方認可的,而你的解決方案不是,iirc。沒有責備:) – 2010-07-29 22:11:34

+1

@orangeoctopus,僅適用於Python2.6 + http://docs.python.org/library/stdtypes.html#str.format – 2010-07-29 22:14:45

12

可以使用運營商%注入字符串轉換成字符串:

"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 
-2

你也可以這樣做:

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

其實,這不起作用..你是不是指'print(「這是」+ name)'? – Lisa 2016-02-25 15:33:57

0

使用

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)) 

這個解決方案是最簡單的讀/理解,對於初學者這樣更好,因爲它只是簡單的字符串連接。