2012-05-03 80 views
22

我想了解用一些其他文本替換字符串子字符串的最佳方法。這裏有一個例子:用Python替換字符串的子字符串

我有一個字符串,一個,可能是像「你好,我的名字是$名稱」。我還有另一個字符串b,我想在子字符串'$ name'的位置插入到字符串a中。

我認爲這將是最容易的,如果可替換的變量指示某種方式。我使用了美元符號,但它可能是花括號之間的字符串,或者您認爲最好的方式。

解決方案: 這是我決定如何做到這一點:

from string import Template 


message = 'You replied to $percentageReplied of your message. ' + 
    'You earned $moneyMade.' 

template = Template(message) 

print template.safe_substitute(
    percentageReplied = '15%', 
    moneyMade = '$20') 
+1

我想問一下重新使用標準格式的方法如果替代品$格式不unchangeble爲{ } –

回答

55

以下是最常見的方式做到這一點:

>>> import string 
>>> t = string.Template("Hello my name is $name") 
>>> print t.substitute(name='Guido') 
Hello my name is Guido 

>>> t = "Hello my name is %(name)s" 
>>> print t % dict(name='Tim') 
Hello my name is Tim 

>>> t = "Hello my name is {name}" 
>>> print t.format(name='Barry') 
Hello my name is Barry 

使用string.Template是簡單易學,應該熟悉來砸用戶的方法。它適合暴露給最終用戶。這種風格在Python 2.4中可用。

percent-style對於很多來自其他編程語言的人來說都很熟悉。有些人認爲這種風格很容易出錯,因爲%(name)s中的尾隨「s」,因爲% - 操作符與乘法具有相同的優先級,並且因爲應用參數的行爲取決於它們的數據類型(元組和字典get特殊處理)。這種風格從一開始就受到Python的支持。

curly-bracket style僅在Python 2.6或更高版本中受支持。它是最靈活的風格(提供一組豐富的控制字符並允許對象實現自定義格式化程序)。

+16

@kwikness - 我很確定雷蒙德暗指[Guido van Rossum](http://en.wikipedia.org/wiki/Guido_van_Rossum)(pyth關於創作者和BDFL(仁慈的生活獨裁者)), Tim Peters([TimSort](http://en.wikipedia.org/wiki/Timsort)fame,寫道[Python of Zen](http://stackoverflow.com)/questions/228181/the-zen-of-python))和[Barry Warsaw](http://barry.warsaw.us/)(在python/jython中很大 - 例如在這個[愚人笑話](http ://www.python.org/dev/peps/pep-0401/)巴里叔叔變成了FLUFL(終身友好的語言叔叔)。 –

8

結帳在python替換()函數。這裏是一個鏈接:

http://www.tutorialspoint.com/python/string_replace.htm

試圖取代已指定一些文本時,這應該是有用的。例如,在鏈路他們告訴你這一點:

str = "this is string example....wow!!! this is really string" 
print str.replace("is", "was") 

對於每一個字"is",它會用這個詞"was"更換。

+3

這實際上是一個很好的例子,說明爲什麼str.replace是*不是* OP所需要的:「this」將變成「thwas」:) (請不要分號分號謝謝) –

11

有很多方法可以做到這一點,更常用的是通過字符串已經提供的設施。這意味着使用%運營商,或更好的是,更新的和推薦的str.format()

例子:

a = "Hello my name is {name}" 
result = a.format(name=b) 

或者更簡單地說

result = "Hello my name is {name}".format(name=b) 

您還可以使用位置參數:

result = "Hello my name is {}, says {}".format(name, speaker) 

或者有明確的指標:

result = "Hello my name is {0}, says {1}".format(name, speaker) 

,它允許您更改在字符串中的字段的順序不改變調用format()

result = "{1} says: 'Hello my name is {0}'".format(name, speaker) 

格式真的很強大。您可以使用它來決定製作字段的寬度,如何編寫數字以及其他格式,具體取決於您在括號內編寫的內容。

如果替換更復雜,您也可以使用str.replace()函數或正則表達式(來自re模塊)。

2

您也可以使用%格式化,但.format()被認爲更現代。

>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3} 
'Your name is tom' 

但它也支持從平常%格式已知的某些類型檢查:

>>> '%(x)i' % {'x': 'string'} 

Traceback (most recent call last): 
    File "<pyshell#40>", line 1, in <module> 
    '%(x)i' % {'x': 'string'} 
TypeError: %d format: a number is required, not str