Python re expr from Perl to Python

Jorge Godoy jgodoy at gmail.com
Sat Jan 6 10:36:14 EST 2007


"Michael M." <michael at mustun.ch> writes:

> In Perl, it was:
>
>
>   ## Example: "Abc | def | ghi | jkl"
>   ##       -> "Abc ghi jkl"
>   ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st pipe).
>   $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g;
>
>   ## -- remove [ and ] in text
>   $na =~ s/\[//g;
>   $na =~ s/\]//g;
>   # print "DEB: \"$na\"\n";
>
>
> # input string
> na="Abc | def | ghi | jkl [gugu]"
> # output
> na="Abc ghi jkl gugu"
>
>
> How is it done in Python?

The simplest form:

>>> na="Abc | def | ghi | jkl [gugu]"
>>> na_out = na.replace('def', '').replace(' | ', ' ').replace('  ', ' ').replace('[', '').replace(']', '').strip()
>>> na_out
'Abc ghi jkl gugu'
>>> 


Another form:

>>> na_out = ' '.join(na.split(' | ')).replace('[', '').replace(']', '').replace(' def', '')
>>> na_out
'Abc ghi jkl gugu'
>>> 


There is the regular expression approach as well as several other
alternatives.  I could list other (simpler, more advanced, etc.) alternatives,
but you can also play with Python by yourself.  If you have a more concrete
specification, send it to the group.



-- 
Jorge Godoy      <jgodoy at gmail.com>



More information about the Python-list mailing list