2012-09-26 42 views
32

我有Python中的字符串替換輸出字符串模式,說The quick @red fox jumps over the @lame brown dog.用Python的功能

我想更換一個與@開始函數的輸出取詞作爲詞論據。

def my_replace(match): 
    return match + str(match.index('e')) 

#Psuedo-code 

string = "The quick @red fox jumps over the @lame brown dog." 
string.replace('@%match', my_replace(match)) 

# Result 
"The quick @red2 fox jumps over the @lame4 brown dog." 

有沒有一個聰明的方法來做到這一點?

+1

你有什麼好。你在一個聲明中這樣做。 – tuxuday

回答

58

您可以將一個函數傳遞給re.sub。該函數將接收一個匹配對象作爲參數,使用.group()將匹配作爲字符串提取。

>>> def my_replace(match): 
...  match = match.group() 
...  return match + str(match.index('e')) 
... 
>>> re.sub(r'@\w+', my_replace, string) 
'The quick @red2 fox jumps over the @lame4 brown dog.' 
+1

美麗。我不知道我可以通過一個函數re.sub,但我覺得我應該能夠。 – nathancahill

1

嘗試:

import re 

match = re.compile(r"@\w+") 
items = re.findall(string) 
for item in items: 
    string = string.replace(item, my_replace(item) 

這將允許您更換任何以@開頭無論你的函數的輸出。 我不是很清楚如果你需要幫助的功能。讓我知道如果是這樣的話

+0

're.findall(pattern,string)' - 請修復 –

+0

這實際上非常有用,因爲它允許您僅替換字符串中的匹配元素。 – Dannid

0

短一個與正則表達式和減少:

>>> import re 
>>> pat = r'@\w+' 
>>> reduce(lambda s, m: s.replace(m, m + str(m.index('e'))), re.findall(pat, string), string) 
'The quick @red2 fox jumps over the @lame4 brown dog.' 
4

我不知道,你可以傳遞一個函數到re.sub()無論是。 @Janne Karila的答案解決了我遇到的問題,這種方法也適用於多個捕獲組。

import re 

def my_replace(match): 
    match1 = match.group(1) 
    match2 = match.group(2) 
    match2 = match2.replace('@', '') 
    return u"{0:0.{1}f}".format(float(match1), int(match2)) 

string = 'The first number is [email protected], and the second number is [email protected]' 
result = re.sub(r'([0-9]+.[0-9]+)(@[0-9]+)', my_replace, string) 

print(result) 

輸出:

The first number is 14.2, and the second number is 50.6000.

這個簡單的例子要求所有的捕獲基團存在(沒有任選的基團)。