2012-08-03 39 views
27

在Python,它是乏味寫:在Ruby中,Python是否有類似「string#{var}」的變量插值?

print "foo is" + bar + '.' 

我可以做這樣的事情在Python?

print "foo is #{bar}."

+0

可能重複[格式的數字爲字符串在Python(http://stackoverflow.com/questions/22617/format-numbers-to-strings-in-python) – 2012-08-03 02:36:06

+0

我想我已經找到了解決方案,你會檢查出來嗎? http://stackoverflow.com/questions/16504732/how-could-i-make-my-python-string-interpolation-implementation-work-accross-impo – SalchiPapa 2013-05-12 10:25:33

+0

的[可能的複製是否有一個Python等同於Ruby的字符串插入?](https://stackoverflow.com/questions/4450592/is-there-a-python-equivalent-to-rubys-string-interpolation) – josemigallas 2017-06-15 08:46:42

回答

38

Python沒有做變量代換 - 這是明確的,而不是隱含的。

但是,您可以使用str.format變量傳遞:

# Rather than this: 
puts "foo is #{bar}" 

# You would do this: 
print "foo is {}".format(bar) 

# Or this: 
print "foo is {bar}".format(bar=bar) 

# Or this: 
print "foo is %s" % (bar,) 

# Or even this: 
print "foo is %(bar)s" % {"bar": bar} 
+1

第三個人看起來整潔,但我記得這種方式有點廢棄?真的嗎? – mko 2012-08-03 02:52:17

+10

還有懶惰的'print'foo是%(bar)s「%locals()'。 – 2012-08-03 02:58:26

+1

@yozloy - 更正它在Python 3中已被棄用(據我瞭解)。 – 2012-08-03 02:58:41

4

String formatting

>>> bar = 1 
>>> print "foo is {}.".format(bar) 
foo is 1. 
+3

或更舊,但仍然流行:print「foo is%s」%str (酒吧) – Edmon 2012-08-03 02:39:48

+0

這應該是現在被棄用,雖然我找不到PEP。 – Josiah 2012-08-03 02:41:23

+0

不推薦使用,只是取代。 – 2012-08-03 02:42:01

7

我從Python Essential Reference瞭解到以下技術:

>>> bar = "baz" 
>>> print "foo is {bar}.".format(**vars()) 
foo is baz. 

這是非常有用的,當我們要引用許多變數在格式化字符串中:

  • 我們不必重複所有vari再次在參數列表中進行比較:將其與基於顯式關鍵字參數的方法(如"{x}{y}".format(x=x, y=y)"%(x)%(y)" % {"x": x, "y": y})進行比較。
  • 如果參數列表中的變量順序與它們在格式化字符串中的順序一致,我們不必一一檢查:將它與基於位置參數的方法(如"{}{}".format(x, y),"{0}{1}".format(x, y)"%s%s" % (x, y)) 。
+2

這是一種很奇怪的方式來傳遞吧...雖然很整潔,但它更貼近Ruby的方式。 – Josiah 2012-08-03 02:48:45

+0

如果您使用的是對象,這看起來像是最好的解決方案。例如,如果您報告的是urllib2.HTTPError,則可以執行'「HTTP錯誤:{error.code} {error.msg}」。format(** vars())'這不適用於format(* *當地人())' – 2014-10-03 08:27:11

2

我更喜歡這種做法,因爲你沒有通過引用變量兩次重複自己:

 
alpha = 123 
print 'The answer is {alpha}'.format(**locals()) 
+0

但是我想這很慢 - 打開一個可能的大字典的params。 – warvariuc 2012-08-03 05:36:40

+0

@warwaruk寫入到std出來是限制因素,打印字符串花費的時間比格式化的10倍以上,而且當地人()返回一個參考,所以我覺得這個方法是非常快 – jcr 2014-03-21 07:55:00

3

有在Ruby中這之間有很大的區別:

print "foo is #{bar}." 

而且這些在Python中:

print "foo is {bar}".format(bar=bar) 

在Ruby示例中,bar評估
在Python的例子,bar只是給你只是用變量的行爲或多或少相同的字典

在這種情況下的一個關鍵,但在一般情況下,轉換的Ruby到Python ISN沒那麼簡單

6

Python 3。6有introduced f-strings

print(f"foo is {bar}.") 

老答案:

從版本3.2 Python有str.format_maplocals()globals()在一起,讓你做快:

Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
>>> bar = "something" 
>>> print("foo is {bar}".format_map(locals())) 
foo is something 
>>> 
18

的Python 3.6 會有literal string interpolation使用f -strings

print(f"foo is {bar}.") 
+2

爲了防止有人疑惑:是的,你可以結合這與說原始字符串,就像這樣'rf「富是{酒吧}」'。 – 2017-02-20 07:40:08

相關問題