string replace shortcut

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Sep 18 09:19:38 EDT 2007


En Tue, 18 Sep 2007 08:44:32 -0300, <vedrandekovic at v-programs.com>  
escribi�:

> Hello,
>
> I am trying to replace some string with list objects:
>
>>>> my_text1="function1 function2"
>>>> from my_module_with_functions_1 import *
>>>> from my_module_with_functions_2 import *
>
> # functions in module " my_module_with_functions_1 ":
> my_func1  it's value "function1"
> my_func2  it's value "function2"
>
> # functions in module " my_module_with_functions_2 ":
> my_func100  it's value "bla bla 1"
> my_func200  it's value "bla bla 2"
>
> ........now, we need find and replace functions from module "
> my_module_with_functions_1 "  and
> replace them with  functions from module " my_module_with_functions_2
> "
>
> with: my_text1.replace(items1,items2)
>
> Result must be:
>
>>>> print my_text1.replace(items1,items2)
> bla bla 1 bla bla 2

I'm unsure what you want. You keep saying "functions" but they are  
apparently strings.
If your problem is how to replace many strings, just do it one at a time  
(asuuming they're unique so the order is not important).

def multi_replace(text, list1, list2):
     for rep1, rep2 in itertools.izip(list1, list2):
         text = text.replace(rep1, rep2)
     return text

py> multi_replace("a sentence with a few words", ["sentence","words"],  
["man","d
ollars"])
'a man with a few dollars'

Now, your problem may be building both lists. They must be syncronized,  
that is, the first element on one list must correspond to the first  
element on the other, and so on. The import statement doesn't guarantee  
any ordering so I think the best way would be to define an __all__  
attribute on both modules, and import that:

 from my_module_with_functions_1 import __all__ as list_of_names_1
 from my_module_with_functions_2 import __all__ as list_of_names_2

new_text = multi_replace(my_text1, list_of_names_1, list_of_names_2)

-- 
Gabriel Genellina




More information about the Python-list mailing list