Academia
Academia

Reputation: 4124

Some tough string manipulation in Python

I have this string in Python:

s = "foo(a) foo(something), foo(stuff)\n foo(1)"

I want to replace every foo instance with its content:

s = "a something, stuff\n 1"

The string s is not constant and the foo content changes every time. I did something using regex, split and regex, but got a very large function. How can I do it in a simple and concise way? Thks in advance.

Upvotes: 2

Views: 168

Answers (2)

Junuxx
Junuxx

Reputation: 14281

Since you say that the content of foo doesn't contain parentheses, Regex really doesn't seem needed. Why don't you just do:

>>> s = "foo(a) foo(something), foo(stuff)\n foo(1)"
>>> s = s.replace('foo(','')
>>> s = s.replace(')','')
>>> print s
'a something, stuff\n 1'

See Python: string.replace vs re.sub

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251598

>>> x = "foo(a) foo(something), foo(stuff)\n foo(1)"
>>> re.sub(r'foo\(([^)]*)\)', r'\1', x)
u'a something, stuff\n 1'

Upvotes: 6

Related Questions