[英]Replacing a substring of a string with Python
我想就用一些其他文本替換字符串的子串的最佳方法得到一些意見。 這是一個例子:
我有一個字符串,a,可能是“你好我的名字是$ name”。 我還有另一個字符串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')
以下是最常見的方法:
>>> 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的方法很容易學習,並且對bash用戶應該很熟悉。 它適合暴露給最終用戶。 這種風格在Python 2.4中可用。
來自其他編程語言的許多人都熟悉百分比風格 。 有些人發現這種風格容易出錯,因為%(name)s
中的尾隨“s”,因為%-operator具有與乘法相同的優先級,並且因為應用參數的行為取決於它們的數據類型(元組和dicts得到特殊處理)。 Python從一開始就支持這種風格。
只有Python 2.6或更高版本支持花括號樣式 。 它是最靈活的樣式(提供豐富的控制字符集並允許對象實現自定義格式化程序)。
有很多方法可以做到這一點,更常用的是通過字符串已經提供的設施。 這意味着使用%
運算符,或者更好的是,使用更新和推薦的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
模塊)。
在python中檢查replace()函數。 這是一個鏈接:
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"
替換它。
實際上這已經在模塊string.Template
實現了。
你可以這樣做:
"My name is {name}".format(name="Name")
它在python中原生支持,你可以在這里看到:
您也可以使用%格式,但.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.