nmarques
nmarques

Reputation: 131

Python - string replacement in a weird way;

Anyone can help with this? Imagine the following:

def example(s):
    s = s.replace('foo', 'foo bar')
    return s

Now this will replace 'foo' with 'foo bar'; But I want to do something a bit different: * Imagine I have 'foo something'; I want the final result to be: 'foo something bar'

What would be the best way to make such check (if there is a 'something', I want to preserve it).

Anyone can help please ?

NM

Upvotes: 1

Views: 140

Answers (5)

nmarques
nmarques

Reputation: 131

I've just fixed it with the following:

def replace_lang_macros(s):
    return re.sub(r'%find_lang(.*)', r'%find_lang\1 %{?no_lang_C}', s)

Thanks all; No matter what stands after %find_lang it remains there... Without raw string notation I get strange symbols, but that wasn't much of a challenge.

Upvotes: 0

Pierre GM
Pierre GM

Reputation: 20339

For the exercise, a clunky way that doesn't use regexp:

def replace_foo(arg):
   content = arg.split()
   idx_foo = content.index("foo")
   content.insert(idx_foo+2, "bar")
   return ' '.join(content)

(but you should really use re...)

Upvotes: 0

John Keyes
John Keyes

Reputation: 5604

For the specific example you mention above:

import re

text = """Line 1 %find_lang %{name} has two %find_lang %{name}
occurences.

Line 4 has one %find_lang %{name}.

%find_lang %{name}

Line 6 is just the search pattern and a new line."""

print re.sub(
        '%find_lang %{name}',
        '%find_lang %{name} %{?no_lang_C}',
        text
    )

Upvotes: 0

Max
Max

Reputation: 20004

import re
mystring = "foo something blah"
re.sub(r"foo\s+(\w+)", r"foo \1 bar", mystring)

Upvotes: 3

Lanaru
Lanaru

Reputation: 9721

Use the re module.

import re
def replace(s):
     return re.sub('foo(.*)', 'foo\1 bar', s)
replace('foo something') #'foo something bar'

Upvotes: 8

Related Questions