开发者

search and replace text in python

I am kinda to python programming

I have no clue how to solve that task:

for line in f:  br
开发者_StackOverflow    m = re.search("f(\S+\s+,\s+\S+)", 
                  "56 - f(32  ,  6*3) + 62 * ( 54 - 3 ) + f(5  , 9+y)")
print m.group()

I have to convert all f(x , y) to x*y.

I haven't got an idea how to solve that. I tried with splitting but didn't worked.

Thanks!


I would recommend a tour towards the python tutorial, perhaps the string section.

After that, the regexp tutorial.


Regular expressions can be a complicated beast, I suggest reading up on them. For this particular scenario re.sub should do the trick.

Here's a sample of what I've come up with using the input you provided.

import re
inp = "56 - f(32  ,  6*3) + 62 * ( 54 - 3 ) + f(5  , 9+y)"

# Matches on characters, arithmetic operations, and digits (hopefully)
pattern = r"f\(\s*([a-z\d\-\+\*/]+)\s*,\s*([a-z\d\-\+\*/]+)\s*\)"

print re.sub(pattern, r"\1 * \2", inp)

This should produce:

56 - 32 * 6*3 + 62 * ( 54 - 3 ) + 5 * 9+y

I am no expert when it comes to regular expressions but hopefully the above will get you started. I doubt the above regex will catch all occurrences and for that I suggest you ask someone with better regex-fu. Merely providing this as an example.


Try re.sub.

regex = re.compile('a+')
x = re.sub(regex, 'd', 'baac')
print(x)

Prints:

bdc


Like this!?

>>> inp = "56 - f(32  ,  6*3) + 62 * ( 54 - 3 ) + f(5  , 9+y)"
>>> import re
>>> re.sub(r'f\((\S+)\s*,\s*(\S+)\)',r'\1*\2',inp)
'56 - 32*6*3 + 62 * ( 54 - 3 ) + 5*9+y'

probably its useful to put the multiplication in parantheses? Then you could use the following regexp:

>>> re.sub(r'f\((\S+\s*),(\s*\S+)\)',r'(\1*\2)',inp)
'56 - (32  *  6*3) + 62 * ( 54 - 3 ) + (5  * 9+y)'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜