69

私はPythonで文字列を持っていますThe quick @red fox jumps over the @lame brown dog.

@で始まる各単語を、その単語を引数として取る関数の出力に置き換えようとしています。

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

これを行う賢い方法はありますか?

4

4 に答える 4

120

に関数を渡すことができますre.sub。この関数は、一致オブジェクトを引数として受け取り、一致.group()を文字列として抽出するために使用します。

>>> def my_replace(match):
...     match = match.group()
...     return match + str(match.index('e'))
...
>>> string = "The quick @red fox jumps over the @lame brown dog."
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'
于 2012-09-26T08:36:33.720 に答える
5

試す:

import re

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

これにより、@ で始まるものを関数の出力に置き換えることができます。この機能についても助けが必要かどうかはよくわかりませんでした。その場合はお知らせください

于 2012-09-26T08:31:47.777 に答える
2

正規表現と削減を使用した短いもの:

>>> 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.'
于 2012-09-26T08:43:12.087 に答える